c - 如果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 是线程本身吗?我在这里有点困惑。主线程执行是否有特定顺序?
解决方案
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
您要求线程等到thread1
终止,然后等到thread2
终止,这就是它的作用。
推荐阅读
- c++ - 在 OpenGL 中为自由类型设置模型矩阵时类似笔的行为
- python - Pipenv 无法安装任何软件包
- python - 将多个用户配置文件链接在一起
- reporting-services - 基于 Getdate() 函数的 SSRS 报告
- python - 在 (Py)Spark DataFrame 中映射值
- c# - 拖放异常。桌面对象
- android - 如何在xml代码中调用finish()
- firebase - Firestore 查询仅需要的字段 (Firebase)
- angular - 如何在 Angular 中清空组件属性,同时保留其类型定义?
- c++ - C++ 中的前缀匹配