C Pthread : Kill other threads gracefully through one thread

标签 c linux multithreading pthreads

我正在处理 C 中的 pthread 问题。

问题背景:有5个线程使用同一个函数,当共享内存中的核心数据达到上限时,这5个线程都应该终止。我使用信号量来确保只有其中一个执行核心数据,这意味着五个中只有一个将获得结束信号,然后它会告诉其余的终止。我写的实现代码是:

#define THREAD_NUM 5;
int thread[THREAD_NUM];
sem_t s;       /*semaphore to synchronize*/
sem_t empty;   /*keep check of the number of empty buffers*/
sem_t full;    /*keep check of the number of full buffers*/


void com_thread(*prt){ // I pass the id of the thread using prt
     while(1){
        sem_wait(&full)
        sem_wait(&s)
        ...do something
        sem_post(&s)
        sem_post(&empty)
     }   
}

while 循环运行时会出现信号,我尝试在以下位置接受信号,然后终止所有线程。

老实说,我需要做的是优雅地结束所有线程,我需要它们返回到主线程进行 thread_join() 并释放内存,而不是简单地退出程序。所以这就是我在这里没有使用 exit() 的原因。

下面的主要思想是当其中一个线程收到信号时终止其他 4 个线程。之后它会自行终止。

但是,它并没有像我预期的那样工作。

#define THREAD_NUM 5;
int thread[THREAD_NUM];
sem_t s;       /*semaphore to synchronize*/
sem_t empty;   /*keep check of the number of empty buffers*/
sem_t full;    /*keep check of the number of full buffers*/


void com_thread(*prt){ // I pass the id of the thread using prt
     while(1){
        sem_wait(&full)
        sem_wait(&s)

        if(signal){
            int i;
            int id = *((int*) prt);
            for (i=0;i<THREAD_NUM;i++){
                if(i != id)
                pthread_exit(&thread[i]);
            }
            pthread_exit(&thread[id]);
        }

        ...do something
        sem_post(&s)
        sem_post(&empty)
     }   
}

有人可以帮我吗?或者,是否有更好的方法来实现这一目标?提前致谢:)

最佳答案

您可以从要终止所有其他线程的线程中使用 pthead_kill。手册页位于 http://linux.die.net/man/3/pthread_kill .如果你想要优雅终止,你应该仔细选择信号。 http://linux.die.net/man/7/signal有更多详细信息。

关于C Pthread : Kill other threads gracefully through one thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36489965/

相关文章:

linux - 以编程方式检测物理内核的数量

java - Android、服务和线程。为什么线程不开始运行直到其他执行结束?

java - Swing:重置 ObjectOutputStream 时出现 EDT NullPointerException

node.js - 如何在 bash 中抑制 npm WARN 弃用消息

c - 复杂数据类型的内存分配

c - 在c中通过引用传递int?

更改c语言中的输入文本颜色

c - C 上的单链表 - 警告 C4047

c# - 如何在 Linux 上的 .NET 6 中写入文件描述符 3 而不是 stdout?

Python Makefile 库