std::this_thread::sleep_for 与std::this_thread::yield的区别

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 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值