小编ove*_*ent的帖子

C 中的 pthreads:如何阻止线程相互干扰?

我是使用 pthreads 的新手。我想创建一个程序,其中六个不同的线程将分别输出不同的数字。线程可以以任何顺序运行,但是,每个线程只能运行一次。

因此,可能的输出是:

Thread: 5
Thread: 2
Thread: 3
Thread: 6
Thread: 1
Thread: 4
Run Code Online (Sandbox Code Playgroud)

或者它可以是任何其他顺序。

#include<stdio.h>
#include<pthread.h>
    
void *apples(void *void_apple_num){
      int *thread_num = (int *) void_apple_num;
      printf("Thread: %d\n", *thread_num);
      return NULL;
}



int main(){
  pthread_t threads[6];
  int apple_num;
  

  for(apple_num=0; apple_num<6; apple_num++){
       pthread_create(&threads[apple_num], NULL, apples, &apple_num);
  }

  for(apple_num=0; apple_num<6; apple_num++){
       pthread_join(threads[apple_num], NULL);
  }    

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,我遇到了线程相互干扰的问题。我不确定某些线程是否运行两次?但是,我认为问题在于某些线程正在使用apple_num来自不同线程指针。

这是我得到的两个示例输出:

输出 1:

Thread: 5
Thread: 0
Thread: 1
Thread: 1
Thread: 2
Thread: 2
Run Code Online (Sandbox Code Playgroud)

输出 2:

Thread: 1
Thread: …
Run Code Online (Sandbox Code Playgroud)

c concurrency multithreading mutex pthreads

2
推荐指数
1
解决办法
97
查看次数

标签 统计

c ×1

concurrency ×1

multithreading ×1

mutex ×1

pthreads ×1