C++11创建线程的高级应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89163592

一 创建一个线程,并传递字符串作为参数

1 代码

#include <iostream>  
#include <thread>  
using namespace std;  
      
void thfunc(char *s)  //线程函数
{  
    cout << "thfunc: " <<s << "\n";   //这里s就是boy and girl
}  
      
int main(int argc, char *argv[])  
{  
    char s[] = "boy and girl"; //定义一个字符串
    thread t(thfunc,s);  //定义线程对象,并传入字符串s
    t.join();   //等待t执行结束
      
    return 0;  
}  

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread -std=c++11
[root@localhost test]# ./test
thfunc: boy and girl

二 创建一个线程,并传递结构体作为参数

1 代码

#include <iostream>  
#include <thread>  
using namespace std;  
   
typedef struct  //定义结构体的类型
{
    int n;
    const char *str;
}MYSTRUCT;

void thfunc(void *arg)  //线程函数
{  
    MYSTRUCT *p = (MYSTRUCT*)arg;
    cout << "in thfunc:n=" << p->n<<",str="<< p->str <<endl; //打印结构体的内容
}  
      
int main(int argc, char *argv[])  
{  
    MYSTRUCT mystruct; //定义结构体
    //初始化结构体
    mystruct.n = 110;
    mystruct.str = "hello world";

    thread t(thfunc, &mystruct);  //定义线程对象t,并把线程函数指针和线程函数参数传入
    t.join();  //等待线程对象t结束
      
    return 0;  
}  

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread -std=c++11
[root@localhost test]# ./test
in thfunc:n=110,str=hello world

三 创建一个线程,传多个参数给线程函数

1 代码

#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;   //修改 *k
}  
      
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,并传入多个参数
    t.join();     //等待线程对象t结束
    cout << "k=" << k << endl;    此时打印应该是5000

    return 0;  
}  

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread -std=c++11
[root@localhost test]# ./test
in thfunc:n=110,m=200,k=5
str=hello world
k=5000

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89163592
今日推荐