码迷,mamicode.com
首页 > 编程语言 > 详细

线程的返回值

时间:2017-01-10 13:05:42      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:amp   turn   char argv   fail   jpg   str   types.h   stdio.h   null   

线程的返回值
当线程退出时,线程可以选择向主线程返回一个值,返回方式一共有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;
}

技术分享

线程的返回值

标签:amp   turn   char argv   fail   jpg   str   types.h   stdio.h   null   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!