pthread_join得到pthread_exit传出来的参数

本文展示了一个使用pthread库创建两个子线程的例子,并演示了如何在主线程中获取子线程修改的数据结构。其中一个子线程修改了全局数据结构的内容,而另一个子线程直接退出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

struct foo
{
	int a,b,c,d;
}w;


void printfoo(const char *s, const struct foo *fp)
{
	printf(s);
	printf(" structure at 0x%x\n", (unsigned)fp);
	printf(" foo.a = %d\n", fp->a);
	printf(" foo.b = %d\n", fp->b);
	printf(" foo.c = %d\n", fp->c);
	printf(" foo.d = %d\n", fp->d);
}

void *thr_fn1(void *arg)
{
	pthread_t  tid;
	tid = pthread_self();
	printf("thread 1: ID is %u\n", (unsigned int)tid);
	printfoo("thread 1:\n", &w);
	w.a = 500;
	w.b = 600;
	w.c = 700;
	w.d = 800;
	pthread_exit((void *)&w);
}

void *thr_fn2(void *arg)
{
	pthread_t tid;
	tid = pthread_self();
	printf("thread 2: ID is %u\n", (unsigned int)tid);
	pthread_exit((void *)0);
}

int main(void)
{
	int err;
	pthread_t tid1, tid2;
	struct foo *fp;
	w.a = 1; w.b = 2; w.c = 3; w.d = 4;

	err = pthread_create(&tid1, NULL, thr_fn1, NULL);
	if(err != 0)
		printf("can't create thread 1: %s\n", strerror(err));
	err = pthread_join(tid1, (void *)&fp);
	if(err != 0)
		printf("can't join with thread 1: %s\n", strerror(err));
	sleep(1);
	printf("parent starting second thread\n");
	err = pthread_create(&tid2, NULL, thr_fn2, NULL);
	if( err != 0)
		printf("can't create thread 2: %s\n", strerror(err));
	sleep(1);
	printfoo("parent: \n", fp);
	return 0;

}

运行结果:

[root@localhost one]# gcc pthread2.c -lpthread
[root@localhost one]# ./a.out
thread 1: ID is 3078536048
thread 1:
 structure at 0x8049b94
 foo.a = 1
 foo.b = 2
 foo.c = 3
 foo.d = 4
parent starting second thread
thread 2: ID is 3078536048
parent: 
 structure at 0x8049b94
 foo.a = 500
 foo.b = 600
 foo.c = 700
 foo.d = 800
[root@localhost one]# 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值