std::this_thread::yield: 当前线程放弃执行,操作系统调度另一线程继续执行。即当前线程将未使用完的“CPU时间片”让给其他线程使用,等其他线程使用完后再与其他线程一起竞争"CPU"。
std::this_thread::sleep_for: 表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU,根据线程需求,等待若干时间。
两者具有相似的作用,但使用目的不同。例如以下两个函数:
#include<thread>
#include<mutex>
#include<iostream>
std::mutex mtx;
bool g_flag = false;
void F1(int n)
{
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
n++;
if(n == 10){
mtx.lock();
g_flag = true;
mtx.unlock();
}else
std::cout<<"F1 n: "<<n<<std::endl;
}
}
void F2(int& n)
{
while (true)
{
mtx.lock();
bool flag = g_flag;
mtx.unlock();
if( flag )
{
n++;
std::cout<<"F2 n: "<<n<<std::endl;
}else
std::this_thread::yield();
}
}
int main(){
int n = 0;
std::thread t1(F1, n), t2(F2, std::ref(n));
t1.join();
t2.join();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
F1线程函数循环体内,每隔1秒钟执行一次操作。
F2线程函数循环体内若标志位被置位则执行一次操作,否则放弃当前线程,让出未用完的CPU时间片,等其他线程使用完后再一起竞争CPU时间,若循环体内不使用yield,则该线程立即与其他线程竞争CPU时间,像此类线程频繁地竞争CPU时间从而影响程序性能
---------------------
作者:Sandy_WYM_
来源:CSDN
原文:https://blog.csdn.net/Sandy_WYM_/article/details/83538635
版权声明:本文为博主原创文章,转载请附上博文链接!