pthread 使用中的问题

本文探讨了一个在多线程环境下遇到的问题:主线程退出时导致子线程输出信息异常。通过一个简单的C语言示例程序,分析了问题产生的原因在于主线程与子线程对标准输出的竞争,并给出了正确的解决方案。

在使用 pthread 多线程测试自己写的 API 的并发性能时,发现 API 里的测试信息都打不出来。写了个最小系统来复现问题。

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

void *readDataFunc(void *args){
	printf("------start read func-----\n");
	int uin = *(int*)args;
	printf("value, %d\n", uin);
	printf("------end read func-----\n");
	return args;
}

int main(int argc, char **argv)
{
	int rts=10;
	pthread_t readThreads;
	pthread_create(&(readThreads), NULL, readDataFunc, &rts);
	return 0;
}

发现有时候什么都不打印,有时候会打印

------start read func-----
------start read func-----

看似线程执行了两次。

后来分析发现是因为 main return 退出的时候会在 stdout 上发生竞争。新线程的 printf 在写完缓冲区之后执行 flush,再要把已经 write 过的数据从缓冲区中删掉,但是在删除之前,main 线程的 exit 也要 flush stdout,就可能把已经 flush 过的数据又 flush 了一遍,输出两次信息,看似执行了两次。

解决方法是在 main 线程中等待新线程执行完成。

pthread_join(readThreads, NULL)

关于线程中线程

之前我还在考虑一个问题,我使用一个 GetLaunchSession 方法获取全局的单例,单例中有个线程去更新配置。那将这个 API 放在多线程中使用,岂不是线程中的线程了。会不会存在什么问题。

其实,是没有线程中线程这种叫法的。

Thread is entity that is global in whole process. It doesn't matter if it is created in one of other thread. The moment it is created, it becomes global and unrelated to thread it created it.

在这样的场景中,我们是需要在线程中创建线程的。比如上面的 main 也是一个线程。

When you're working with servers, you can create thread for each connected client from thread where you are listening for clients.

##参考 pthread_create 一个线程却执行两次

Is it ok to create thread in thread?

转载于:https://my.oschina.net/lvyi/blog/849225

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值