在使用 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.
Is it ok to create thread in thread?