首页 > 解决方案 > 为什么 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完成运行,想法是两者都运行并且结果不同于

标签: cmultithreading

解决方案


因为这个函数是阻塞的。如果我们打开 man 我们会看到以下内容:

pthread_join() 函数等待线程指定的线程终止。如果该线程已经终止,则 pthread_join() 立即返回。thread 指定的线程必须是可连接的。


推荐阅读