c++11 yield函数的使用
生活随笔
收集整理的這篇文章主要介紹了
c++11 yield函数的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
yield函數時c++11的新特性,它在std::this_thread::yield命名空間中實現,函數聲明如下:
void yield() noexcept;其作用是當前線程“放棄”執行,讓操作系統調度另一線程繼續執行
比如說你的線程需要等待某個操作完成,如果你直接用一個循環不斷判斷這個操作是否完成就會使得這個線程占滿CPU時間,這會造成資源浪費。這時候你可以判斷一次操作是否完成,如果沒有完成就調用yield交出時間片,過一會兒再來判斷是否完成,這樣這個線程占用CPU時間會大大減少。,例如:
while(!isDone()); // Bad while(!isDone()) yield(); // Good代碼示例:
#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; }運行結果:
參考資料:
yield - C++ Reference
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的c++11 yield函数的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++11中thread join和de
- 下一篇: 投资1000万!宁德时代设立新公司 涉及