首页 > 编程语言 > 详细

线程的返回值

时间:2017-01-10 13:03:06      阅读:156      评论:0      收藏:0      [点我收藏+]

线程的返回值
当线程退出时,线程可以选择向主线程返回一个值,返回方式一共有4种
1\如果要返回int类型,可以使用pthread_exit((int)* return_value);
2\使用全局变量返回(这个最简单)
3\使用malloc所分配的空间
4\直接返回字符串,如pthread_exit("return value");

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <pthread.h>

void *thread1(void)
{
        printf("this is thread 1, return value : hello world, I love you!\n");
        pthread_exit("hello world, I love you!");
}

int main(int argc, char argv[])
{
        int result = 0;
        void *return_value;
        pthread_t th1;
        result = pthread_create(&th1, NULL, thread1, NULL);
        if(result != 0)
        {
                printf("create pthread failed, app exit!\n");
                exit(-1);
        }
        printf("create pthread succeed!\n");
        pthread_join(th1,&return_value);
        printf("return value : %s\n", (char *)return_value);
        return 0;
}

技术分享

线程的返回值

原文:http://www.cnblogs.com/foggia2004/p/6268747.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!