【发布时间】:2021-05-23 06:36:58
【问题描述】:
我的线程有问题。我正在尝试创建 10 个线程,并为每个线程打印线程 ID。我可以打印线程 ID,但问题是所有线程都打印出相同的线程 ID。
这是我的代码:
主要:
int main(void)
{
int check_error;
pthread_t clientThread[10];
printf("creating a client thread..!\n");
fflush(stdout);
for(int i=0; i<10;i++){
check_error=pthread_create(&clientThread[i], NULL, mqClient, NULL);
if(check_error!=0)
printf("Error when creating thread: %s", strerror(check_error));
else
pthread_join(clientThread[i], NULL);
}
return EXIT_SUCCESS;
}
mqClient:
void * mqClient(void * arg){
pthread_mutex_lock(&mutex);
mqd_t mq_on_server;
struct pt planet;
char thread_id[30];
sprintf(thread_id, "%d", pthread_self());
usleep(1000);
int response = MQconnect(&mq_on_server, "/servermq");
if(response==0){
printf("Something went wrong with MQconnect\n");
}
else{
printf("\nEnter planet name: ");
scanf("%s", planet.name);
printf("\nEnter planet X-position: ");
scanf("%lf", &planet.sx);
printf("\nEnter planet Y-position: ");
scanf("%lf", &planet.sy);
printf("\nEnter planet X-velocity: ");
scanf("%lf", &planet.vx);
printf("\nEnter planet Y-velocity: ");
scanf("%lf", &planet.vy);
printf("\nEnter planet mass: ");
scanf("%lf", &planet.mass);
printf("\nEnter planet life time: ");
scanf("%d", &planet.life);
strcpy(planet.pid, thread_id);
printf("id: %s", planet.pid);
printf("\n---------------------------------------");
}
MQwrite (mq_on_server, &planet);
int c;
while ( (c = getchar()) != '\n' && c != EOF);
pthread_mutex_unlock(&mutex);
return NULL;
}
当测试两个线程时,这是输出(观察相同的线程 ID):
Planet name: dsadas
Planet X-position: 321.000000
Planet Y-position: 321.000000
Planet X-velocity: 321.000000
Planet Y-velocity: 312.000000
Planet mass: 321.000000
Planet life time: 321
Planet thread ID: 1058301696
---------------------------------------
Planet name: ytyr
Planet X-position: 3123.000000
Planet Y-position: 54.000000
Planet X-velocity: 56.000000
Planet Y-velocity: 231.000000
Planet mass: 546.000000
Planet life time: 231
Planet thread ID: 1058301696
每个线程的线程 ID 应该是唯一的,所以知道为什么我会得到这种输出吗?
【问题讨论】:
-
在剥离所有 MQ 代码后会出现同样的问题。当然,您可以在适当的minimal reproducible example 的“最小”小贩上更加努力地推动天然气。不过我会说这个。假设
pthread_self()和int是同义词,甚至兼容,是highly speculative。 -
我确实解决了。问题出在 main 函数中。 pthread_join 必须在单独的 for 循环中。
-
所以基本上你的线程没有同时运行
pthread_joinmulti-threading有什么意义?
标签: c linux multithreading operating-system pthreads