【发布时间】:2020-04-20 12:36:22
【问题描述】:
我试图给线程一个 id,然后我想打印我给的每个线程 id,但是我猜有一个关于互斥锁的情况,我想我正在处理关键部分,但似乎我不能.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
struct info{
int id;
int flag;
};
void *print_info(void* arg){
struct info *arg_struct = (struct info*) arg;
pthread_mutex_lock(&m);
printf("%d ", arg_struct->id);
pthread_mutex_unlock(&m);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int number = 10;
pthread_t tid[number];
for (int i = 0; i < number; ++i) {
int info[2];
info[0] = i;
info[1] = 0;
pthread_create(&tid[i], NULL, print_info, &info);
}
for (int i = 0; i < number; ++i) {
pthread_join(tid[i], NULL);
}
return 0;
}
这是输出: 1 2 3 4 5 6 7 8 9 9
每次我执行它都会有所不同,但或多或少的概念是相同的,它不会打印一些值,它会多次打印一些值。
但预期的输出是这样的: 0 1 2 3 4 5 6 7 8 9
[或者一些不按顺序的东西,但我猜到每个值都会被准确地打印出来] 谢谢
【问题讨论】:
-
info是本地块内部。当它超出范围时,此本地被破坏,因此您正在访问线程函数中的悬空指针。将此数组分配到堆上,例如使用malloc/calloc函数。 -
你之前说的我试过了,结果还是一样,你说一次后我试过了,没有任何变化
-
线程函数将指向
int[2]的指针转换为指向struct info的指针。不好。 -
还有一场竞赛,因为新生成的线程访问了
arg指向的内容,而创建线程的循环已经用新值i覆盖了int[0]。不好。
标签: c multithreading pthreads mutex