C++面向对象多线程编程简介

多线程编程引发的问题:死锁、无限延迟、数据竞争等。并发编程包括多任务(多进程)和多线程。

使用多线程编程时需包含头文件<thread>,具体测试程序代码如下:

#include <iostream>
#include <thread>
using namespace std;
void function_1(){
	cout<<"Hello world!"<<endl;	
}
void function_2(string str){
	cout<<str<<endl;
}
void function_3(string& str){
	str="我修改了,哈哈!";
}
void function_4(string str){
	//str="我修改了,哈哈!";
	cout<<str<<endl;
}
class factor{
	public:
		void operator()(){
			cout<<"Thread factor run"<<endl;
		}
};
int main(){
	thread t1(function_1);//通过函数名创建线程 
	cout<<this_thread::get_id()<<endl;	//主线程的id 
	cout<<t1.get_id()<<endl;//t1线程的id 
	factor fac;
	thread t2(fac);	//通过类对象创建线程 
	//thread t2(factor());//通过调用类函数创建线程 
	thread t3(function_2,"你好,世界!"); //带有值传递的创建线程 
	string text="woxiugaile,hehe";
	thread t5(function_4,move(text));//带有移动传递的创建线程,text被移动后为空	
	t5.join();//若t5还没有执行完成,则主线程等待t5执行完毕再执行。 
	cout<<text<<endl;
	thread t4(function_3,ref(text));//若想传递引用时,实参需使用ref(),同时函数形参为&类型 ,能否实现线程间共享内存管理 
	t4.join();	 
	cout<<text<<endl; 
	for(int i=0;i<10;i++){
		cou
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值