Linux下C++11的线程类用法(可连接线程和可分离线程thread)

Linux下调用多线程有两种方式,一种是利用POSIX线程库,一种是用C++11中的线程类,本文用的是后者。其中,Linux下用C++11创建多线程分为可连接的和不可连接的。

可连接线程:需要调用thread成员函数thread::join()阻塞等待线程结束并且回收资源;thread默认创建的线程是可连接线程!

不可连接线程(也就是分离线程):直接调用thread::detach()即可在线程结束后自动回收资源。

函数pthread_exit(NULL)(放在主函数里面)表示主线程结束后,该线程所在进程并不会立即结束,要等所有线程结束后主进程才会结束。

下面将分别列举可连接线程和分离线程实例。

 

实例1  创建一个可连接线程,并传入字符串

步骤1:在Linux目录下新建一个文件名为thread_input_char.cpp空白文件,输入下列代码:

#include <iostream>
#include <thread>
using namespace std;

void thfunc(char *s)
{
	cout<<"child thread char =="<< s << "\n";	//打印传入的字符串
}

int main(int argc, char *argv[])
{
	char s[] = "I am a main thread char";
	thread t(thfunc,s);	//创建线程,传入线程函数,带字符串
	t.join();
	return 0;
}

步骤2:在终端terminal输入下列命令,生成可执行程序thread_input_char,然后运行可执行程序,结果如下图所示:

g++ -o thread_input_char thread_input_char.cpp -lpthread -std=c++11

 

实例2  创建一个分离线程,并且传入结构体和多个变量

步骤1:在Linux目录下新建一个文件名为thread_input_struct.cpp空白文件,输入下列代码:

#include <iostream>
#include <thread>
using namespace std;

typedef struct	//
{
	int num;
	const char *str;	//z
}MYSTRUCT;

void thfunc(void *arg, int m, int *k, char s[])
{
	MYSTRUCT *p = (MYSTRUCT*)arg;	//
	cout<<"child thread p->num =="<< p->num <<"\nchild thread p->str =="<< p->str<<endl;	//d
	cout<<"child thread m =="<<m<<"\nchild thread k =="<<*k<<"\nchild thread str =="<<s<<endl;	//
	*k=7777;
}

int main(int argc, char *argv[])
{
	MYSTRUCT mystruct;	//d
	mystruct.num = 666;
	mystruct.str =  "I am a struct";
	
	int m=300,k=12;
	char str[]="I am a string";	

	thread t(thfunc,&mystruct,m,&k,str);	//s
	t.detach();	//

	cout<<"changed value k =="<<k<<endl;	//7777
	pthread_exit(NULL);	//

	cout<<"I can not run!"<<endl;
	return 0;
}

步骤2:在终端terminal输入下列命令,生成可执行程序thread_input_char,然后运行可执行程序,结果如下图所示:

g++ -o thread_input_struct thread_input_struct.cpp -lpthread -std=c++11

 

 

参考内容:

《Linux C与C++ 一线开发实践》  397-399页

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三公子Tjq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值