gpt4 book ai didi

c - 识别 C 上的线程

转载 作者:太空宇宙 更新时间:2023-11-04 06:18:28 25 4
gpt4 key购买 nike

所以我正在学习如何在 C 上使用线程,并且我写下了这段代码。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define number 3

void *funct(void *tid){
printf("Thread %d\n", *((int*)tid));
sleep(10);
printf("Thread %d finishes\n", *((int*)tid));
pthread_exit(NULL);
}

int main() {
pthread_t threads[number];
int i, status;
printf("Pid: %d\n", getpid());
for (i = 0; i < number; i++) {
printf("Thread number %d\n", i);
status = pthread_create(&threads[i], NULL, funct, (void*)&i);

if(status != 0){
printf("Error en la creación del hilo. La función devuelve %d\n", status);
exit(-1);
}
}

for (i = 0; i < number; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}

我的问题是我想在 funct 上用它们的编号来识别它们,但有时输出是错误的。

Pid: 10142
Thread number 0
Thread number 1
Thread number 2
Thread 2
Thread 1
Thread 0
Thread 0 finishes
Thread 0 finishes
Thread 0 finishes

它不应该打印 Thread 0 finishes 3 次。我想 tid 的内容在线程调用之间发生变化,这就是它打印另一个值的原因。我该如何解决这个问题?

最佳答案

你有一个 data race因为您将同一变量 i 的地址传递给所有线程函数。您可以改为使用临时数组来传递线程“数字”。

   int thr_id[number];
for (i = 0; i < number; i++) {
thr_id[i] = i;
printf("Thread number %d\n", i);
status = pthread_create(&threads[i], NULL, funct, &thr_id[i]);
...

另外,请注意在 C 中不需要强制转换为 void 指针。

关于c - 识别 C 上的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40398254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com