/*
* yield
* 实现:std::this_thread::yield 命名空间实现
* 作用:当前线程放弃执行,让操作系统调度另一线程继续执行
* 例如:比如说你的线程需要等待某个操作完成,如果你直接使用一个循环
* 不断判断这个操作是否完成就会使的这个线程占满cpu时间,这会造成资源
* 浪费。此时,你可以判断一次操作是否完成,如果没有完成就调用yield
* 交出时间片,过一会再来判断是否完成,这样这个线程占用CPU时间会大大
* 减少。
* 例如:
*
* while(!isDone()); //bad
* while(!idDone()) yield(); //good
*
*/
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
#include <mutex>
std::mutex m_mutex;
std::atomic<bool> ready(false);
void count1m(int id)
{
while (!ready) {
/*
若线程还没有创建,将当前线程分配的cpu时间片,让调度器安排给其他线程
由于使用yield函数,在 not ready的情况下,避免空循环,在一定程度上
提高了cpu使用率
*/
std::this_thread::yield();
}
for(int i=0;i<1000000;i++)
{
std::lock_guard<std::mutex>lck(m_mutex);
std::cout<<" this thread id:"<< id<<std::endl;
}
}
int main(int,char*[])
{
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;
for(int i=0;i<10;i++)
{
threads[i].join();
}
std::cout<<"\n";
}
参考:
https://blog.csdn.net/c_base_jin/article/details/79246211 使用该例程