c - 为什么 thread2 等待 thread1 结束?
问题描述
#include <stdio.h>
#include <pthread.h>
#define NR_LOOP 10000
static int resource = 0;
static void *thread1_function();
static void *thread2_function();
int main(void){
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,*thread1_function,NULL);
pthread_create(&thread2,NULL,*thread2_function,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("The value of the resource is: %d\n",resource);
return 0;
}
static void *thread1_function(){
for(int i = 0; i < NR_LOOP; i++){
resource++;
}
return NULL;
}
static void *thread2_funcion(){
for(int i = 0; i < NR_LOOP; i++){
resource--;
}
return NULL;
}
我正在尝试一个简单的线程代码来实践他们在课堂上教我的东西,问题是thread2等待thread1完成运行,想法是两者都运行并且结果不同于
解决方案
因为这个函数是阻塞的。如果我们打开 man 我们会看到以下内容:
pthread_join() 函数等待线程指定的线程终止。如果该线程已经终止,则 pthread_join() 立即返回。thread 指定的线程必须是可连接的。
推荐阅读
- python - PyAutoGUI,停止命令
- r - 我应该将 R 包 BNlearn 用于我的数据的交叉验证中的什么损失函数?
- kotlin - 如果为空,如何将新列表分配给可为空的字段,或者只是将元素添加到 Kotlin 中的现有列表?
- reactjs - 带有 NextJs 的 ModuleParseError
- ansible - 在 Ansible 中覆盖默认变量的属性
- java - Android:手机重启后设置闹钟/提醒
- android - 电话不显示反应原生(世博会)上的所有文本
- java - Log Miner 无法捕获数据
- sql - SQL, query to check and list distinct entries that occur in another table within a specific time frame
- flutter - Iterable 具有价值,但是当我尝试将其传递给函数或将其转换为列表时,它似乎为空