C++线程的创建简单应用

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

一 点睛

1 pthread_create的用法

https://baike.baidu.com/item/pthread_create/5139072?fr=aladdin

二 创建一个简单的线程,不传参数

1 代码

#include <pthread.h>
#include <stdio.h>
#include <unistd.h> //sleep

void *thfunc(void *arg)   //线程函数
{
    printf("in thfunc\n");
    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;
    }
     
    sleep(1);  // main线程挂起1秒钟,为了让子线程有机会执行
    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
in main:thread is created

3 说明

这个例子中,首先创建一个线程,在线程函数中打印一行字符串后结束,而主线程在创建子线程后,会等待一秒,这样不至于因为主线程过早结束而导致进程结束,进程结束后,子线程就没机会执行了。如果没有等待函数sleep,则可能子线程的线程函数还没来得及执行,主线程就结束了,这样导致了子线程的线程函数都没有机会执行,因为主线程已经结束,整个应用程序已经退出了。

二 创建一个线程,并传入整型参数

1 代码

#include <pthread.h>
#include <stdio.h>

void *thfunc(void *arg)
{
    int *pn = (int*)(arg); //获取参数的地址
    int n = *pn;
     
    printf("in thfunc:n=%d\n", n);
    return (void *)0;
}
int main(int argc, char *argv [])
{
    pthread_t tidp;
    int ret, n=110;

    ret = pthread_create(&tidp, NULL, thfunc, &n);//创建线程并传递n的地址
    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:n=110
in main:thread is created

3 说明

这个例子和上面这个例子有两点不同:一是创建线程的时候,把一个整型变量的地址作为参数传给线程函数;二是等待子线程结束没有用sleep函数,而是用pthread_join函数,sleep只是等待一个固定的时间,有可能在固定的时间内子线程早已结束,或者子线程运行时间大于这个固定时间,因此用它来等待子线程结束并不精确,而用函数pthread_join则会一直等到子线程结束后才执行该函数后面的代码。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89056375