【问题标题】:Stop thread only if n threads are running including itself仅当 n 个线程(包括其自身)正在运行时才停止线程
【发布时间】:2020-08-18 03:03:47
【问题描述】:

我被要求在一个进程(48)中创建一些线程,但是只有当包括它自己在内的 6 个线程正在运行时,14 号线程才能停止。然而他们进入了一个无限循环。

这是我的进程中的线程应该执行的函数:

pthread_mutex_lock_t lock;
pthread_mutex_cond_t cond;
reached_6_threads = false;
    void *thread_function_P6(void *args)
    {
        th *t = (th *)args;
        printf("started thread %d", t->id);
        if (t->id != 14)
        {
            pthread_mutex_lock(&lock);
            while (th_no > 6)
            {
                    pthread_cond_wait(&cond, &lock);
            }
            if(!reached_6_threads && th_no==6){
                pthread_cond_wait(&cond, &lock);
                th_no--;
                reached_6_threads = true;
            }
            th_no++;
            if (!reached_6_threads && th_no == 6)
            {
                pthread_cond_broadcast(&cond);
                pthread_mutex_unlock(&lock);
            }
        }
        printf("threads running: %d\n", th_no);
        printf("stopped thread %d", t->id);
        pthread_exit(0);
    }

lock 和 cond 在创建线程之前被初始化。

【问题讨论】:

    标签: c multithreading synchronization barrier


    【解决方案1】:

    我不确定我是否理解您,但请在您的代码中注意:

    a) 大部分代码都处于互斥锁下,这意味着它们不能真正并行运行

    b) 线程 14 的运行与运行线程的数量无关

    反正卡住的原因是:

    a) 你的线程几乎是按顺序运行的

    b) 线程 1-5 跳过 while 和两个 if,th_no 现在是 5(假设它被初始化为 0?)

    c) 线程 6 将 th_no 提升到 6 并进入第二个 if,执行广播但没有线程卡在该条件锁上

    d) 线程 7 及以上的线程首先进入 if 并等待永远不会中断的条件锁

    我会建议以下解决方案。由于我还没有完全理解你,所以在这个例子中只允许运行 6 个线程,而不管它们的 id 是多少,你只需要做一些小的改动。

    pthread_mutex_lock(&lock); 
    while(th_no >= 6){pthread_cond_wait(&cond, &lock);}
    th_no++;
    pthread_mutex_unlock(&lock); //Raise counter and unlock the mutex
    
    /*
    Thread function code here. Pay attention to critical code and use mutex.
    */
    
    pthread_mutex_lock(&lock); //Acquire lock once again, decrease counter and broadcast if number of threads is ok now
    th_no--;
    if(th_no <= 5){
       if(pthread_cond_broadcast(&cond)){
           // Error as it should return 0 on success
       }
    }
    pthread_mutex_lock(&unlock);
    

    如果这有帮助,请告诉我

    【讨论】:

    • 是的 th_no 被初始化为 0
    • 你的建议很有用,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-02-08
    • 2021-07-05
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多