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

标签 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完成运行,想法是两者都运行并且结果与

最佳答案

因为这个函数是阻塞的。如果我们打开 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/

相关文章:

c - 动态分配结构数组

c - 如何通过二分查找获得所有匹配的值?

c - 为什么 lex 不能识别我的正则表达式定义

java - ConcurrentMap 条目同步而不阻塞整个 map

c - 从子线程调用时 getaddrinfo 和 gethostbyname 崩溃?

c - C中的void和static void函数有什么区别?

c# - 将 C header 转换为 C# - 结构内固定字符数组的 ByValArray 与 ByValTStr

java - 当另一个线程终止时终止 Thread.Sleep() ?

java - Akka future 指导

c - 信号 "auto-block"(当执行进入处理程序函数时)是否会阻止另一个此类信号传递到另一个线程?