c-如何终止正在等待信号量操作的线程

我正在编写一个使用共享内存和ipc信号灯的程序.有一个主服务器进程创建共享内存和信号灯.任何数量的客户端进程都可以连接到共享内存,并在允许时对其进行读写.信号量提供了阻止机制来控制读取和写入.一切正常,除非我尝试终止客户端.用于访问共享内存的信号量块在一个线程中,并且在进程终止时,我无法释放信号量块,因此线程可以正确退出.我将如何处理?这是针对Linux的.

具体来说,有一个shm和两个sems.第一学期阻止写作,第二学期阻止阅读.当客户端有要写入的内容时,它将等待写入sem为0,然后将其设置为1,进行写入,然后将读取sem设置为0,这将释放等待的服务器以读取客户端写入的内容.读取后,服务器会将写入sem设置回0,并且下一个客户端将开始写入.它挂在一个semop调用上,当读sem为0时释放该semop调用.此semop调用在线程中,我需要弄清楚如何在退出主线程之前正确退出该线程.

这是我想做的但不起作用的示例(睡眠伪装成挂断电话):

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

void termination_handler (int signum) {
    printf( "Got Signal\n" );
}

void *threadfunc( void *parm ) {
    struct sigaction action;

    action.sa_handler = termination_handler;
    sigemptyset( &action.sa_mask );
    action.sa_flags = 0;

    sigaction( SIGUSR1, &action, NULL );

    printf("Thread executing\n");

    sleep( 100 ); // pretending to be the semaphore

    pthread_exit( NULL );
}

int main() {
    int       status;
    pthread_t threadid;
    int       thread_stat;

    status = pthread_create( &threadid, NULL, threadfunc, NULL );

    if ( status <  0) {
        perror("pthread_create failed");
        exit(1);
    }

    sleep( 5 );

    status = pthread_kill( threadid, SIGUSR1 );

    if ( status <  0 )
        perror("pthread_kill failed");

    status = pthread_join( threadid, (void *)&thread_stat );
    if ( status <  0 )
        perror("pthread_join failed");

    exit( 0 );
}

解决方法:

他说,这是针对Linux的.

如果您可以确切说出自己的做法,这将很有用.我假设您正在阻止sem_wait或sem_timedwait.如果您的线程在那阻塞,您想中断它,可以使用pthread_kill.

pthread_kill(blocking_thread_id, SIGUSR1);

当然,您需要设置适当的信号处理程序(man sigaction)以捕获SIGUSR1,并且需要检查sem_wait()的返回码以获取EINTR,在这种情况下,您可以知道被中断并可以做任何想做的事情.没有锁.

如果您使用的是进程,则只需使用kill()而不使用pthread_kill()提供进程ID. (对不起,起初我误读并认为您正在使用线程)

上一篇:c-pthread的计时器中断


下一篇:对象变量在PHP pthread中丢失上下文