c - C 中的信号接收器线程和 pthread_join 停止程序

标签 c multithreading

我正在尝试构建一个有 2/3 线程的基本程序。主线程、信号发送线程和接收线程。我正在尝试使主线程同时启动信号发送器和接收器线程。然后,信号发送线程应该向接收线程发送 10 个 SIGUSR1 信号并增加全局计数器。接收器线程应该接收 10 个信号,同时为每个接收到的信号增加自己的计数器。

我遇到的问题是在最后将线程重新连接在一起,特别是连接接收器线程。大多数情况下,如果我尝试将它们重新连接在一起,程序就会停止,我认为是因为接收器线程尚未完成其工作(也许它丢失了信号?),因此它永远不会完成。我想也许是这种情况,所以我在信号线程中引入了一个等待命令来减慢它的速度,但这并没有改变任何东西。

如果我注释掉 pthread_join(receiver, NULL) 那么程序就会运行,但大多数时候它只捕获一个信号。我认为这是因为接收器线程没有太多时间运行。 (尽管有时它会捕获不同的数量,具体取决于它被抢占的时间?)

将 pthread_join(receiver, NULL) 保留在程序中会使程序停止 19/20 次,但程序会在 1/20 次中返回 10 个发送的信号和 10 个接收的信号。这让我相信它与抢占有关,但我不明白为什么它首先会停止。

现在我只有接收线程接收线程,而接收到的计数器< 10。理想情况下,我只想将其保留在 while(1) 循环中,但话又说回来,我不知道如何将其加入回来进入主线程而不卡住所有内容。

如果有人能帮助我弄清楚为什么信号被错过/为什么程序被卡住,我将不胜感激。我怀疑我没有为接收器正确设置信号掩码,但我不知道我还应该怎么做。这是代码:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <signal.h>

void *receivetest(void *args);
void *signaltest(void *args);


int received = 0;
int sent = 0;
pthread_t signaler;
pthread_t receiver;
sigset_t mask;

int main(){

    //setting up the signal mask
    sigemptyset(&mask);
    sigaddset(&mask, SIGUSR1);

    //creation of both threads
    pthread_create(&receiver, NULL, receivetest, NULL);
    pthread_create(&signaler, NULL, signaltest, NULL);


    pthread_join(signaler, NULL);
    pthread_join(receiver, NULL);

    //printing results after joining them back
    printf("I'm the main function\n");
    printf("Receieved: %d, sent: %d\n", received, sent);


}

void *signaltest(void *args){
    int i = 0;
    for(i=0;i<10;i++){ //sends 10 signals to receiver thread
        pthread_kill(receiver, SIGUSR1);
        sent++;
    }
}

void *receivetest(void *args){
    int c; //sigwait needs int 
    pthread_sigmask(SIG_BLOCK, &mask, NULL); //sets up the signal mask for this thread
    while(received < 10){ //waits for 10 signals and increments receieved
        sigwait(&mask, &c);
        received++;
    }
}

最佳答案

信号不是这样工作的。如果线程接收到一个信号,而该信号已处于挂起状态,则不会发生任何情况。请使用适当的线程间通信方法,而不是信号。

关于c - C 中的信号接收器线程和 pthread_join 停止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433734/

相关文章:

c - 如何将马拉雅拉姆语打印为 c/c++ 程序输出?

php - 多台服务器使用单个 MySQL 数据库

java - 停止并重新启动已运行的线程

java - 无法取消 WorkerThread 。取消函数什么时候执行,仍然执行

c - 一个 C cgi 脚本,用于从 sqlite3_column_blob 指针提供二进制文件

java - SSLSockets 和密码规范问题

java - 复杂对象的普通 Java 线程池与 Aparapi GPU

python - 是否有任何理由使用 Python threading.local() 而不是 ContextVar(在 >= 3.7 中)

c - 使用 SQLite3 和 C 的段错误

c - 警告 C4013 : undefined; assuming extern returning int