【发布时间】:2016-08-05 18:44:12
【问题描述】:
我有一个庞大的多线程代码库。有 100 个线程。 99 个线程有一个函数do_thread_operations 与它们中的每一个关联。第 100 个线程有一个与之关联的操作 monitor_99threads。
do_thread_operations 有无限循环,所以它们永远不会停止。 monitor_99threads 跟踪时间。启动一分钟后,它必须关闭所有 99 个线程并返回主线程。
以下是我的代码。
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
int *to_close_thread;
void * do_thread_operations(void * thread_data){
int i = *(int *)thread_data;
while (1){
//do something
if (to_close_thread[i]) break;
}
}
void * monitor_99threads(void * data){
int i = 0;
while(1){
i++;
if(i > 60){
for (int i = 0; i < 99; ++i){
printf("Closing %d", i);
to_close_thread[i] = 1;
}
}
}
}
int main(){
to_close_thread = (int *)malloc(99 * sizeof(int));
memset(to_close_thread, 0, 99*sizeof(int));
pthread_t threads[100];
for (int i = 0; i < 99; ++i){
int j = i;
pthread_create(&threads[i], NULL, do_thread_operations, (void *)&j);
}
pthread_create(&threads[99], NULL, monitor_99threads, NULL);
for (int i = 0; i < 100; ++i){
pthread_join(threads[i], NULL);
}
}
问题是虽然关闭了打印,但线程并没有跳出它们的循环。
【问题讨论】:
-
您将
j传递给线程,然后更改main中j的值。您需要一个数组id[100],然后将&id[i]传递给线程。 -
@user3386109 不,我正在重新声明它。
-
可能是同步问题。你不能假设你的线程会按照创建的顺序读取变量 j。
-
@clarasoft-it,我明白这一点。但即便如此,线程也会在某个时候停止,对吧?它永不中断。
-
@SonuMishra 理论上,
j在块的末尾超出范围,因此不复存在。这意味着线程(理论上)正在尝试访问不存在的东西(这比仅访问其值已更改的东西更糟糕)。实际上,编译器在堆栈上为j分配四个字节,然后为j的每个新实例重用这四个字节。为了更好地理解这一点,您应该使用-S进行编译并查看编译器生成的汇编代码。
标签: c multithreading pthreads