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

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

1 代码

#include 
#include 


void *thfunc(void *arg)
{
    char *str;
    str =(char *)arg;  //得到传进来的字符串
    printf("in thfunc:str=%s\n", str); //打印字符串
    return (void *)0;
}
int main(int argc, char *argv [])
{
    pthread_t tidp;
    int ret;
    
    const char *str = "hello world";

    ret = pthread_create(&tidp, NULL, thfunc, (void *)str);//创建线程并传递str
    if (ret)
    {
        printf("pthread_create failed:%d\n", ret);
        return -1;
    }
    pthread_join(tidp, NULL); //等待子线程结束
    printf("in main:thread is created\n");
     
    return 0;
}

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread
[root@localhost test]# ./test
in thfunc:str=hello world
in main:thread is created

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

1 代码

#include 
#include 

typedef struct  //定义结构体的类型
{
    int n;
    const char *str;
}MYSTRUCT;
void *thfunc(void *arg)
{
    MYSTRUCT *p = (MYSTRUCT*)arg;
    printf("in thfunc:n=%d,str=%s\n", p->n,p->str); //打印结构体的内容
    return (void *)0;
}
int main(int argc, char *argv [])
{
    pthread_t tidp;
    int ret;
    MYSTRUCT mystruct; //定义结构体
    //初始化结构体
    mystruct.n = 110;
    mystruct.str = "hello world";

    ret = pthread_create(&tidp, NULL, thfunc, (void *)&mystruct);//创建线程并传递结构体地址
    if (ret)
    {
        printf("pthread_create failed:%d\n", ret);
        return -1;
    }
    pthread_join(tidp, NULL); //等待子线程结束
    printf("in main:thread is created\n");
     
    return 0;
}

2 运行

[root@localhost test]# ./test
in thfunc:n=110,str=hello world
in main:thread is created

三 创建一个线程,共享进程数据

1 代码

#include 
#include 

int gn = 10; //定义一个全局变量,将会会在主线程和子线程中用到
void *thfunc(void *arg)
{
    gn++;    //递增1
    printf("in thfunc:gn=%d,\n", gn); //打印全局变量gn值
    return (void *)0;
}

int main(int argc, char *argv [])
{
    pthread_t tidp;
    int ret;
     
    ret = pthread_create(&tidp, NULL, thfunc, NULL);
    if (ret)
    {
        printf("pthread_create failed:%d\n", ret);
        return -1;
    }
    pthread_join(tidp, NULL); //等待子线程结束
    gn++; //子线程结束后,gn再递增1
    printf("in main:gn=%d\n", gn); //再次打印全局变量gn值
     
    return 0;
}

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread
[root@localhost test]# ./test
in thfunc:gn=11,
in main:gn=12

3 说明

全局变量gn首先在子线程中递增1,子线程结束后,再在主线程中递增1.两个线程都对同一全局变量进行了访问。

你可能感兴趣的:(C++)