首页 技术 正文
技术 2022年11月12日
0 收藏 339 点赞 5,036 浏览 1120 个字

c++11中新支持了thread这个库,常见的创建线程、join、detach都能支持。

join是在main函数中等待线程执行完才继续执行main函数,detach则是把该线程分离出来,不管这个线程执行得怎样,往下继续执行main函数。

join操作会等待线程执行完毕,然后回收该线程资源,detach操作则不会等待线程完成,线程资源的回收由用init进程完成。(感谢https://www.cnblogs.com/liangjf/p/9801496.html的分享)

下面给出两个例子,一个是普通函数放在线程里面执行,另一个是类成员函数放在线程里面执行。

一、普通函数放在线程里面执行

#include<iostream>
#include<thread>
using namespace std;void compute(int *a,int *b,int* c)
{
this_thread::sleep_for(chrono::seconds(5));
*c=*a+*b;
}
int main()
{
int a=1,b=2,c=10;
int *a1=&a,*b1=&b,*c1=&c;
thread t1(compute,a1,b1,c1);//thread重载形式比较多,这里是一种重载方式。函数地址、三个参数
t1.join();//如果是join,那么等待5秒之后,返回c为3,;如果是detach,那么cout不会等待5秒,而是输出c为10,然后结束main函数
cout<<c<<endl;
return 0;
}

二、类成员函数放在线程里面执行

class class1
{
public:
void compute(int *a,int *b,int *c)
{
this_thread::sleep_for(chrono::seconds(5));
*c=*a+*b;
}
thread computethread(int *a,int *b,int *c)
{
return thread(&class1::compute,this,a,b,c);//返回一个thread类型,创建完thread之后,就开始执行线程中的函数
                                        //thread重载类型比较多,这里是一种重载方式。函数地址、指针this、三个参数
}
};
int main()
{
int a=1,b=2,c=10;
int *a1=&a,*b1=&b,*c1=&c;class1 class11;
thread t1=class11.computethread(a1,b1,c1);//调用类中的函数
t1.join();//等待5秒,然后c为3
cout<<c<<endl;
return 0;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,490
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,905
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,738
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,491
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,129
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,292