C++11 std::this

tech2022-07-06  211

其作用是当前线程“放弃”执行,让操作系统调度另一线程继续执行。

比如说你的线程需要等待某个操作完成,如果你直接用一个循环不断判断这个操作是否完成就会使得这个线程占满CPU时间,这会造成资源浪费。这时候你可以判断一次操作是否完成,如果没有完成就调用yield交出时间片,过一会儿再来判断是否完成,这样这个线程占用CPU时间会大大减少。

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

Output:

race of 10 threads that count to 1 million: thread : 0 thread : 5 thread : 2 thread : 1 thread : 6 thread : 3 thread : 8 thread : 4 thread : 7 thread : 9
最新回复(0)