创建线程(POSIX 个线程)
Creating threads (POSIX threads)
我想知道为什么即使 Slave 线程在代码中排在第一位,Master 还是先执行 printf()
?
还有,为什么他们有相同的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)
抱歉,我是新手,答案可能很简单,我不知道。
当这个程序执行时,事件的顺序是这样的:
- 主程序执行完毕
- 它启动了子线程。
- 巧合的是 (!) 它成功地在 ...
之前打印了消息
- ...新启动的子线程打印了它的消息。
- 然后子线程死了,然后...
- ...等待它死掉...主线程也死掉了。
如果你 运行 这个程序很多次,那么最终你可能会遇到子 "beat its parent to the punch." 的情况(但这也与底层操作系统逻辑有关,它确保控制台的输出总是由 "entire strings." 组成,两个 processes/threads 中的任何一个都有相同的机会首先获得它们的字符串,但是您永远不会看到由两个字符串 组成的控制台输出混合在一起。)
源代码中的语句顺序完全无关。
多个线程是独立调度的,所以内核可能会决定先调度新线程还是先调度旧线程,这取决于它的优先级以及系统上还有什么运行。 运行程序多次可能会产生不同的结果,甚至。
两个线程共享相同 PID 的原因是因为 POSIX 说它们必须。有一个进程,即使有多个线程。内核在内部跟踪两个具有不同 PID 的线程,但 glibc 公开了一个 PID(主线程的 PID)作为进程的 PID。
我想知道为什么即使 Slave 线程在代码中排在第一位,Master 还是先执行 printf()
?
还有,为什么他们有相同的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)
抱歉,我是新手,答案可能很简单,我不知道。
当这个程序执行时,事件的顺序是这样的:
- 主程序执行完毕
- 它启动了子线程。
- 巧合的是 (!) 它成功地在 ... 之前打印了消息
- ...新启动的子线程打印了它的消息。
- 然后子线程死了,然后...
- ...等待它死掉...主线程也死掉了。
如果你 运行 这个程序很多次,那么最终你可能会遇到子 "beat its parent to the punch." 的情况(但这也与底层操作系统逻辑有关,它确保控制台的输出总是由 "entire strings." 组成,两个 processes/threads 中的任何一个都有相同的机会首先获得它们的字符串,但是您永远不会看到由两个字符串 组成的控制台输出混合在一起。)
源代码中的语句顺序完全无关。
多个线程是独立调度的,所以内核可能会决定先调度新线程还是先调度旧线程,这取决于它的优先级以及系统上还有什么运行。 运行程序多次可能会产生不同的结果,甚至。
两个线程共享相同 PID 的原因是因为 POSIX 说它们必须。有一个进程,即使有多个线程。内核在内部跟踪两个具有不同 PID 的线程,但 glibc 公开了一个 PID(主线程的 PID)作为进程的 PID。