【发布时间】:2020-03-15 14:11:56
【问题描述】:
我想知道为什么 Master 会先执行printf(),即使 Slave 线程在代码中排在第一位?
另外,为什么它们有相同的 PID(主从)?
void* pthread_function(int id) {
printf("[%s] Slave thread %d (PID=%d,TID=%ld)\n",timestamp(),id,getpid(),pthread_self());
pthread_exit(NULL);
}
int main(int argc,char** argv) {
// Create slave thread
long int i = 1;
pthread_t thread;
pthread_create(&thread,NULL,(void* (*)(void*))pthread_function,(void*)(i));
// Print message
printf("[%s] Master thread (PID=%d,TID=%ld)\n",timestamp(),getpid(),pthread_self());
// Wait for threads
pthread_join(thread,NULL);
// Terminate process OK
return 0;
}
输出是
[2019:11:20 00:25:25:853640] Master thread (PID=5338,TID=140000137201472)
[2019:11:20 00:25:25:853795] Slave thread 1 (PID=5338,TID=140000128689920)
对不起,我是新手,答案可能很简单,我不知道。
【问题讨论】:
标签: c linux unix pthreads posix