为什么线程2等待线程1结束?

时间:2019-09-13 20:53:33

标签: c multithreading

#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完成运行,想法是运行和结果都不同于

1 个答案:

答案 0 :(得分:-1)

因为此功能正在阻止。如果我们打开男人,我们将阅读以下内容:

  

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

相关问题