我的C程序由两个线程组成,由main
线程启动。程序启动时,main
使用pthread_create
创建两个线程。这些线程th1
和th2
对全局int变量S
执行一些求和/减法运算。
th1
和th2
可能会在某些时候退出,具体取决于某些条件。
线程main
启动th1
和th2
,然后应该等待并退出,具体取决于
S
达到大于数字的值th1
和th2
退出无论先来条件是什么,main
都会退出并打印出来。写主要退出条件的正确方法是什么?
请注意,这是一项大学练习,因此解决方案应该合理简单,并且基于一组有限的C库,包括pthread.h
。
我无法在pthread_join
和th1
上使用th2
,因为在子线程退出之前,该数字可能会超过阈值(条件1)。 有没有办法检查main
子线程是否再次运行?
我的解决方案使用pthread_cond_t
中的main
。条件的逻辑检查是运行线程的数量和整数比较。创建线程时,我将其注册(递增threads
计数器)。当它退出时,我注销它。所有更改都包含在互斥锁中。
int main() {
pthread_t th1, th2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&run, NULL);
srand(time(NULL));
int ret;
// ...
if (pthread_create(&th1, NULL, alpha, NULL) == 0) {
thread_register();
}
if (pthread_create(&th2, NULL, beta, NULL) == 0) {
thread_register();
}
for (;;) {
pthread_mutex_lock(&mutex);
while(threads > 0 && S < 1000) {
pthread_cond_wait(&run, &mutex);
}
pthread_cancel(th1);
pthread_cancel(th2);
break;
pthread_mutex_unlock(&mutex);
}
// ...
}
当子线程关闭或更改pthread_cond_signal
时,子线程会发送main
以唤醒S
。
通过这种方式,每次main
唤醒时,它都可以检查子线程是否消失(threads == 0
或S <
阈值。)