#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;
}
我正在尝试一个简单的线程代码来实践他们在类里面教给我的内容,问题是线程2等待线程1完成运行,想法是两者都运行并且结果与
最佳答案
因为这个函数是阻塞的。如果我们打开 man 我们会看到以下内容:
The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately. The thread specified by thread must be joinable.
关于c - 为什么线程2要等待线程1结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57930227/