c++ 线程sleep_C++11多线程

9984dae382c9803b2ed745adf5401535.png

1、std::thread

在C++11之前,C++语言层面是不支持多线程的,想利用C++实现并发程序,借助操作系统的API实现跨平台的并发程序存在着诸多不便,当C++11在语言层面支持多线程后,编写跨平台的多线程代码就方便了许多。

C++11提供的std::thread在开发多线程方面带来了便捷。

#include <iostream>
#include <thread>
​
void threadfunc()
{
    
        std::cout << "thread func" << std::endl;
}
​
​
int main()
{
    
    std::thread t1(threadfunc);
    t1.join();   //等待threadfunc运行结束
 
    return 0;
}
​

首先定义线程对象t1,线程函数threadfunc运行在线程对象t1中,当线程创建成功并执行线程函数后,一定要保证线程函数运行结束才能退出,这里调用了join()函数阻塞线程,直到threadfunc()运行结束,回收对应创建线程的资源。如果不阻塞线程,就不能保证线程对象t1threadfunc()运行期间有效,下面不调用join()阻塞线程。

#include <iostream>
#include <thread>
​
void threadfunc()
{
    
    std::cout << "thread func" << std::endl;
}
​
​
int main()
{
    
    std::thread t1(threadfunc);
    //t1.join();   //等待threadfunc运行结束
 
    return 0;
}
​

在运行时引起了程序崩溃。

de034c38f45c4cc1069a838279fe05a7.png

除了调用join()阻塞线程,保证线程对象在线程函数运行期间的有效性,还可以通过线程分离的手段实现,调用detach()函数使得线程对象与线程函数分离,这样,在线程函数运行期间,线程对象与线程函数就没有联系了,此时的线程是作为后台线程去执行,detach()后就无法再和线程发生联系,也不能通过join()来等待线程执行完毕,线程何时执行完无法控制,它的资源会被init进程回收,所以,通常不采用detach()方法。

#include <iostream>
#include <thread>
​
void threadfunc()
{
    
    std::cout << " detach thread func" << std::endl;
     
}
​
int main()
{
    
    
    std::thread t1(threadfunc);
    t1.detach();      //线程分离
​
    return 0;
}

这里调用detach()实现线程分离,但是运行后,主线程退出的时候threadfunc()还没有输出“detach thread func”threadfunc()什么时候运行结束也无法确定,为了看到所创建的线程运行结果,在主线程等待一下再退出。

#include <iostream>
#include <thread>
#include <chrono>   //时间
​
void threadfunc()
{
    
    std::cout << "detach thread func" << std::endl;
}
​
​
int main()
{
    
    
    std::thread t1(threadfunc);
    t1.detach();
    while (true)
    {
    
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));//睡眠1000毫秒
        break;
    }
    
    return 0;
}

此时运行结果:

detach thread func

通过std::thread创建的线程是不可以复制的,但是可以移动。

#include <iostream>
#include <thread>
#include <chrono>
​
void threadfunc()
{
    
   
    std::cout << "move thread func" << std::endl;
    
    
}
​
​
int main()
{
    
    
    std::thread t1(threadfunc);
    std::thread t2(std::move(t1));
   
    t2.join();
    while (true)
    {
    
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));//睡眠100
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值