c - 多个线程接收一个信号

标签 c multithreading pthreads signals posix

我正在尝试编写一个将创建 10 个线程的程序。这些线程在收到 SIGUSR1 信号后应该全部停止,而在收到 SIGUSR2 后应该继续做他们正在做的事情。

我已经写了这段代码(顺便说一句。你能检查一下它的正确性吗?谢谢!)但我认为当信号 SIGUSR1 发生时只有 1 个线程会接收并处理它(这意味着只有 1 个线程会继续其工作...)。

如何让所有正在等待的线程继续工作?

void handle_sigusr1()
{
    int sig;
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGUSR2);
    printf("Thread waiting for some signal SIGUSR2! \n");
    sigwait(&set, &sig);
}

void install_sigusr1()
{
  struct sigaction setup_action;
  sigset_t block_mask;

  sigfillset(&block_mask);
  setup_action.sa_handler = handle_sigusr1;
  setup_action.sa_mask = block_mask;
  setup_action.sa_flags = 0;
  if (sigaction (SIGUSR1, &setup_action, 0) == -1)
    fprintf(stderr, "sigaction2 err");
}

void* test_thread_func(void * data)
{
    while(1)
    {
        ...
        Some SIGUSR1 signal may occur ...
        ...
    }
}

void create_threads()
{
    pthread_t TH[10];
    int i;
    sigset_t set;
    sigfillset(&set);
    sigdelset(&set, SIGUSR1);
    sigdelset(&set, SIGUSR2);
    pthread_sigmask(SIG_SETMASK, &set, NULL);
    install_sigusr1();
    /* Block all signals except for SIGUSR1 and SIGUSR2. New Threads will
         inherit the sigmask ...*/
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    for(i = 0; i < 10; i++)
    {
        pthread_create(TH[i], &attr, test_thread_func, 0);
    }
    // now we unblock SIGINT so that the main thread only can handle SIGINT signal
    sigdelset(&set, SIGINT);
    // we dont want the main thread to handle SIGUSRs signals ...
    sigaddset(&set, SIGUSR1);
    sigaddset(&set, SIGUSR2);
    pthread_sigmask(SIG_SETMASK, &set, NULL);
    while(1);
}

最佳答案

How do I make all the threads that are waiting continue their work?

pthread_cond_broadcast()函数应解除当前在指定条件变量 cond 上阻塞的所有线程。

I've written this piece of code( btw. Can you also please check it for correctness ?)

对于这篇文章,您的完整代码。这是我从你的问题中可以告诉你的。

关于c - 多个线程接收一个信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324787/

相关文章:

c - 如何阅读整个单词,而不仅仅是第一个字符?

c - c 函数中的可变数量参数

c++ - Qt中线程间通信的实现

c# - 一种主/从锁定系统?

c++ - 在 C++ 中使用线程调用具有多个参数的非静态函数

c - 为什么默认堆栈大小为 0

c - 写入通过结构传递给线程的 mmap 输出 (C)

c - 是否有任何用于绘制图片和制作.jpg 文件的C 库?

c - strtok 中的段错误

c - 什么时候使用 fork 或线程?