gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:13:49 25 4
gpt4 key购买 nike

我正在尝试编写一个将创建 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com