【发布时间】:2020-03-05 07:07:56
【问题描述】:
我读到 main() 本身就是单线程,所以当我像这样在我的程序中创建 2 个线程时;
#include<stdio.h>
#include<pthread.h>
#include<windows.h>
void* counting(void * arg){
int i = 0;
for(i; i < 50; i++){
printf("counting ... \n");
Sleep(100);
}
}
void* waiting(void * arg){
int i = 0;
for(i; i < 50; i++){
printf("waiting ... \n");
Sleep(100);
}
}
int main(){
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, counting, NULL);
pthread_create(&thread2, NULL, waiting, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
int i = 0;
for(i; i < 50; i++){
printf("maining ... \n");
Sleep(1000);
}
}
在这种情况下,main 真的是一个线程吗? 在那种情况下,如果 main 处于睡眠状态一段时间,main 不应该将 CPU 交给其他线程吗? main 是线程本身吗?我在这里有点困惑。 主线程执行是否有特定顺序?
【问题讨论】:
-
将
pthread_join作为代码的最后一行。现在main挂在他们身上。 -
想想
pthread_join的真正作用...花点时间阅读它的手册页。 -
如果我更改 pthread_join 并使其成为最后一条语句。它仍然先打印线程,最后打印主线程
-
main函数中的循环大约需要 50 秒(50乘以一秒的睡眠),但线程循环只需大约 5 秒(50乘以 @987654328 @第二次睡眠)。这意味着两个创建的线程将比“主”线程更快地完成很多。但是应该有一些(一些)"maining ..."输出混合在创建线程的输出中。您需要将输出向上滚动到顶部才能看到它。 -
我得到了一个新答案,上面写着“main 不是线程而是函数”?这是正确的@Someprogrammerdude
标签: c multithreading pthreads