C++11this_threadyeild(12)


C++11this_threadyeild(12)

原文地址:http://www.cplusplus.com/reference/thread/this_thread/yield/

function
<thread>

std::this_thread::yield

void yield() noexcept;
Yield to other threads

The calling thread yields, offering the implementation the opportunity to reschedule.
挂起当前线程的运行,给其他线程运行的机会。

This function shall be called when a thread waits for other threads to advance without blocking.

该方法应该在一个线程等待其他线程资源的时候不阻塞地调用。(即等待其他资源的时候,应该挂起该线程)


Parameters

none


Return value

none


Example

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;
}

Possible output (last line may vary):

race of 10 threads that count to 1 million...
6189370542



Exception safety

No-throw guarantee: never throws exceptions.



—————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:coderguang@gmail.com

2014-9-4

于GDUT

——————————————————————————————————————————————————————————————————




发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注