E V*_*avi 5 c unix linux pthreads
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg)
{
printf("hello, world \n");
return 0;
}
int main(void)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_func, NULL);
pthread_create(&t2, NULL, thread_func, NULL);
printf("t1 = %d\n",t1);
printf("t2 = %d\n",t2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的程序创建了两个线程,每个线程打印“Hello World”。
所以,根据我的理解,“Hello world”应该最多打印 2 次。
然而,在执行相同程序多次(背对背),存在其中正在打印“世界你好”的情况更大于2倍。所以我不清楚它是如何打印出意外次数的?
以下是示例输出:
[rr@ar ~]$ ./a.out
t1 = 1290651392
t2 = 1282258688
hello, world
hello, world
[rr@ar ~]$ ./a.out
t1 = 1530119936
t2 = 1521727232
hello, world
hello, world
hello, world
Run Code Online (Sandbox Code Playgroud)
如上图,程序执行多次后,打印了3次“hello, world”。任何人都可以请告知为什么它被打印了 3 次?
当主程序终止时,子线程也会终止。
可能会发生两个子线程都在主任务完成之前执行的情况。在这种情况下,您会看到两个“hello worlds”以及问题中显示的输出。
也可能发生主程序在一个或两个线程打印输出之前完成的情况。在这种情况下,您可以看到一个或根本看不到“hello world”。
我不认为该程序单次运行会打印 3 次。我假设您正在循环中执行该程序,并且两次运行的输出混合在一起。添加:例如,想象以下场景: RUN1:打印两个数字,然后调度子线程,每个子线程打印一个“hello world”,然后调度回 RUN1 main 并完成程序。接下来,启动RUN2。在这种情况下,两个子线程都在主程序打印数字之前被调度。
所以你会看到类似的输出:
t1=346236763 (RUN1 - main)
t2=876237623 (RUN1 - main)
hello, world (RUN1 - subthread)
hello, world (RUN1 - subthread)
hello, world (RUN2 - subthread)
hello, world (RUN2 - subthread)
t1=3786768623 (RUN2 - main)
t2=7843473478 (RUN2 - main)
Run Code Online (Sandbox Code Playgroud)
输出可能会被错误地解释为单次运行写入了 4 个“hello worlds”。