多线程编程引发的问题:死锁、无限延迟、数据竞争等。并发编程包括多任务(多进程)和多线程。
使用多线程编程时需包含头文件<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