this_thread::yield可以让线程放弃执行,让os重新调度:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int g_data = 0;
void doFunc()
{
while(g_data < 5)
{
this_thread::sleep_for(chrono::nanoseconds(1));
++g_data;
}
}
int main()
{
int i = 0;
thread t(doFunc);
while(1)
{
if(g_data < 1)
{
++i;
this_thread::yield;
}
else
{
break;
}
}
cout<<"loop in while "<<i<<" times"<<endl;
cout<<"wait t join"<<endl;
t.join();
cout<<"t1 join"<<endl;
return 0;
}
this_thread::yield相当于为忙等待提供了一个机会,可以主动让出线程的时间片,让os重新进行调度,但是下一个被调度进来的线程是哪个由os来决定,有可能是别的线程,也有可能还是当前线程。

本文探讨了C++11中的this_thread::yield函数,该函数用于线程执行控制。它允许线程自愿放弃执行,邀请操作系统进行线程调度。这可能导致执行权转移给其他线程,但也可能再次分配给当前线程。

9664

被折叠的 条评论
为什么被折叠?



