首页 > 解决方案 > 如果main也是c中的一个线程,为什么它不与其他线程一起运行

问题描述

我读到 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 是线程本身吗?我在这里有点困惑。主线程执行是否有特定顺序?

标签: cmultithreadingpthreads

解决方案


 pthread_join(thread1, NULL);
 pthread_join(thread2, NULL);

您要求线程等到thread1终止,然后等到thread2终止,这就是它的作用。


推荐阅读