天天看点

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      
Linux下C++11的线程类用法(可连接线程和可分离线程thread)

实例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