当条件或子线程退出时退出主线程

时间:2015-02-09 13:32:06

标签: c multithreading pthreads

我的C程序由两个线程组成,由main线程启动。程序启动时,main使用pthread_create创建两个线程。这些线程th1th2对全局int变量S执行一些求和/减法运算。

th1th2可能会在某些时候退出,具体取决于某些条件。

线程main启动th1th2,然后应该等待并退出,具体取决于

  1. 条件:S达到大于数字的值
  2. th1th2退出
  3. 无论先来条件是什么,main都会退出并打印出来。写主要退出条件的正确方法是什么?

    请注意,这是一项大学练习,因此解决方案应该合理简单,并且基于一组有限的C库,包括pthread.h


    我无法在pthread_jointh1上使用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 == 0S <阈值。)

0 个答案:

没有答案