SIGIO 只通知线程池中的最后一个线程

SIGIO only notifies last thread in threadpool

我想编写一个程序,在 SIGIO 时向我的线程池中的所有线程发出信号。我写了下面的代码,但似乎一个套接字一次只能由一个线程拥有,因此只会通知我线程池中的最后一个线程事件。有没有什么方法可以在不使用专用信号捕获线程并且不中断主进程的情况下获得我想要的行为?

void sigFunc(int signo){
    printf("SIGNAL %li!\n", gettid());
    return;
}

static void* poolFunc(){
    printf("Pool func... %li\n", gettid());

    fcntl(lsocket, F_SETOWN, gettid());

    for(;;)
        sleep(1);

    return NULL;
}

int main(int argc, char *argv[]){
    unsigned char val;
    int lsocket;
    pthread_t pool[4];

    lsocket = socket(AF_INET, SOCK_STREAM, 0);

    // Omitted 15 lines of setting up lsocket, this part is boring

    fcntl(lsocket, F_SETFL, fcntl(lsocket, F_GETFL) | O_ASYNC);

    signal(SIGIO, sigFunc);

    for(val=0; val < 4; val++){
        if(pthread_create(&pool[val], NULL, poolFunc, NULL) != 0){
            printf("Creation of thread pool failed!\n");
            exit(1);
        }

        if(pthread_detach(pool[val]) != 0){
            printf("Failed to detach thread in pool...?\n");
            exit(1);
        }
    }

    printf("Starting main loop...\n");

    for(;;)
        sleep(1);
}

输出:

$ ./program
Pool func... 17580
Pool func... 17582
Pool func... 17581
Pool func... 17583
Pool func... 17584
Starting main loop...
SIGNAL 17584!
SIGNAL 17584!
SIGNAL 17584!
SIGNAL 17584!
SIGNAL 17584!
^C

$ ./program
Pool func... 17621
Pool func... 17620
Pool func... 17623
Pool func... 17624
Pool func... 17622
Starting main loop...
SIGNAL 17622!
SIGNAL 17622!
SIGNAL 17622!
SIGNAL 17622!
SIGNAL 17622!
^C

信号处置在进程级别。

这意味着进程中只有一个线程会收到发送到进程的信号。

换句话说:从进程外部只能向进程的一个 线程发送信号。

发信号 所有 个进程中的线程 pthread_kill() 可以被每个进程的 自己的 线程使用。为此,该进程需要跟踪其所有现有(已创建且仍处于活动状态)线程。