一 代码
#include <iostream>
#include <thread>
using namespace std;
void thfunc(int n,int m,int *k,char s[]) //线程函数
{
cout << "in thfunc:n=" <<n<<",m="<<m<<",k="<<*k<<"\nstr="<<s<<endl;
*k = 5000;
}
int main(int argc, char *argv[])
{
int n = 110,m=200,k=5;
char str[] = "hello world";
thread t(thfunc, n,m,&k,str); //定义线程对象
t.detach(); //分离线程
cout << "k=" << k << endl; //这里输出5
pthread_exit(NULL); //main线程结束,但进程并不会结束,下面一句不会执行
cout << "this line will not run"<< endl; //这一句不会执行
return 0;
}
二 运行
[root@localhost test]# g++ -o test test.cpp -lpthread -std=c++11
[root@localhost test]# ./test
k=5
in thfunc:n=110,m=200,k=5
str=hello world
三 说明
这个例子中,调用了detach来分离线程,这样主线程可以不用等子线程结束而自己先结束。为了展示效果,在主线程中调用pthread_exit(NULL)来结束主线程,在main线程中调用pthread_exit(NULL)的时候,将结束main线程,但进程并不立即退出,要等所有的线程全部结束才会结束,所以我们看到子线程函数打印的内容。主线程会打印k,这是因为打印k的时候线程还没切换。这个例子中C++11和POSIX联合作战,充分体现了C++程序的强大。