yield函數時c++11的新特性,它在std::this_thread::yield命名空間中實現,函數聲明以下:css
void yield() noexcept;
其做用是當前線程「放棄」執行,讓操做系統調度另外一線程繼續執行ios
好比說你的線程須要等待某個操做完成,若是你直接用一個循環不斷判斷這個操做是否完成就會使得這個線程佔滿CPU時間,這會形成資源浪費。這時候你能夠判斷一次操做是否完成,若是沒有完成就調用yield交出時間片,過一下子再來判斷是否完成,這樣這個線程佔用CPU時間會大大減小。,例如:c++
while(!isDone()); // Bad
while(!isDone()) yield(); // Good
代碼示例:markdown
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
#include <mutex>
std::mutex g_mutex;
std::atomic<bool> ready(false);
void count1m(int id)
{
while (!ready)// wait until main() sets ready...
{
//若線程還有沒建立的,將當前線程分配的cpu時間片,讓調度器安排給其餘線程,
//因爲使用了yield函數,在 not Ready 狀況下,避免了空循環,在必定程度上,能夠提升cpu的利用率
std::this_thread::yield();
}
for ( int i = 0; i < 1000000; ++i) {}
std::lock_guard<std::mutex> lock(g_mutex);
std::cout << "thread : "<< id << std::endl;
}
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;
}
運行結果:
函數
參考資料:
http://blog.csdn.net/tanningzhong/article/details/78248258
http://www.cplusplus.com/reference/thread/this_thread/yield/ui