函式
<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


異常安全

無異常保證: 絕不丟擲異常。

另見