Linux多线程编程-线程函数返回值(返回复杂数据类型)

引言

通过几个实验练习,学习线程之间连接的具体实现。下面列举了两个例子,一个是子线程返回简单数据类型;另一个是子线程返回复杂数据类型。

实现代码

子线程返回复杂数据类型

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

struct member {
    int a;
    char *b;
};

void *create(void *arg) {
    struct member *temp = (struct member*)malloc(sizeof(struct member));
    temp->a = 2;
    temp->b = "HelloWorld!";
    printf("Thread created successfully\n");
    return (void*)temp;
}

int main(int argc, char *argv[]) {
    int error;
    pthread_t threadId;
    struct member *c;
    error = pthread_create(&threadId, NULL, create, NULL);
    if(error) {
        printf("Thread create error!\n");
        exit(1);
    }
    printf("I am main\n");
    error = pthread_join(threadId, (void**)&c);	//注意pthread_join()的函数声明
    if(error) {
        printf("Thread is not exit!\n");
        exit(1);
    }
    printf("c->a = %d  \n", c->a);
    printf("c->b = %s  \n", c->b);
    sleep(1);
    return 0;
}

注意

  • 这里定义存储被等待线程的返回值的指针为struct member *c;要注意在pthread_join()中进行强制类型转换,即将member** 转换为 void**。具体代码为(void**)&c,其中&cmember**类型。
  • 在子线程调用作为参数的函数内,要注意返回变量的生命周期。这里采用了动态分配存储空间的方式,保证了返回的指针所指向的内容对应的内存空间不会因为子线程的结束而被释放,从而得到预期结果。

pthread_join()

功能 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。
头文件 : #include <pthread.h>
函数声明:int pthread_join(pthread_t thread, void **retval);
参数说明:thread: 线程标识符,即线程ID,标识唯一线程。retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功,非0是失败。

最后

  • 由于博主水平有限,难免有疏漏之处,欢迎读者批评指正!
发布了18 篇原创文章 · 获赞 16 · 访问量 2438

猜你喜欢

转载自blog.csdn.net/weixin_43587255/article/details/105742397
今日推荐