函数
<thread>

std::this_thread::yield

void yield() noexcept;
将执行权让给其他线程
调用该函数的线程将让出执行权,为实现提供重新调度的机会。

当线程等待其他线程前进而不阻塞时,应调用此函数。

参数



返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// this_thread::yield example
#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::yield
#include <atomic>         // std::atomic

std::atomic<bool> ready (false);

void count1m(int id) {
  while (!ready) {             // wait until main() sets ready...
    std::this_thread::yield();
  }
  for (volatile int i=0; i<1000000; ++i) {}
  std::cout << id;
}

int main ()
{
  std::thread threads[10];
  std::cout << "race of 10 threads that count to 1 million:\n";
  for (int i=0; i<10; ++i) threads[i]=std::thread(count1m,i);
  ready = true;               // go!
  for (auto& th : threads) th.join();
  std::cout << '\n';

  return 0;
}

可能的输出(最后一行可能不同)
race of 10 threads that count to 1 million...
6189370542


异常安全

无异常保证: 绝不抛出异常。

另见