接下来我们看一下线程退出函数和等待函数。

 #include <pthread.h>

       void pthread_exit(void *value_ptr);

value_ptr:是线程的返回值。有pthread_join()检测获得。

功能:线程退出

#include<pthread.h>

       int pthread_join(pthread_t thread, void**value_ptr);

功能:等待指定的线程结束。

返回值:成功返回0

参数:

thread:等待线程的ID(标示符)

value_ptr:用户自定义的指针,用来保存被等待线程的返回值。

这个函数是线程阻塞函数,调用它的函数将一直阻塞到被等待的线程结束为止,当函数返回值,被等待线程的资源被回收。

我们看个例子:

#include<stdio.h>

#include<stdlib.h>

 

void *th_fun1(void*arg)

{

        int i=10/2;

        printf("%s",arg);

        while(i-->0)

                fputs("new thread1\n",stdout);

        pthread_exit ((void*)1);

}

 

void *th_fun2(void*arg)

{

        int i=10/2;

        printf("%s",arg);

        while(i-->0)

                fputs("new thread 2\n",stdout);

pthread_exit((void*)2);

}

 

int main()

{

        int ret;

        pthread_t tid1,tid2;

       if((ret=pthread_create(&tid1,NULL,th_fun1,"new thread 1  created!\n"))==-1)

        {

                perror("pthread_createerror ");

                exit(EXIT_FAILURE);

        }

       if((ret=pthread_create(&tid2,NULL,th_fun2,"new thread 2  created!\n"))==-1)

        {

                perror("pthread_createerror ");

                exit(EXIT_FAILURE);

        }

        void *fret1;

void *fret2;

        pthread_join(tid1,&fret1);

        pthread_join(tid2,&fret2);

    printf("fret1=%d\n",(int)fret1);

    printf("fret2=%d\n",(int)fret2);

        return 0;

}

 

GitHub 加速计划 / li / linux-dash
13
2
下载
A beautiful web dashboard for Linux
最近提交(Master分支:4 个月前 )
186a802e added ecosystem file for PM2 5 年前
5def40a3 Add host customization support for the NodeJS version 5 年前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐