Is there a way to ensure atomicity while having a multithreaded program with signal handlers?

前端 未结 3 1484
离开以前
离开以前 2021-01-23 16:10

If I have a program like this (in pseudocode):

mutex_lock;
func() {
    lock(mutex_lock);
    // Some code (long enough to make a
    // race condition if no pro         


        
3条回答
  •  隐瞒了意图╮
    2021-01-23 16:42

    You need two locks. The one used inside your func(), and one to protect the process's signal mask.

    You have to make masking and unmasking the signal atomic also:

    static  pthread_mutex_t mask_mutex = PTHREAD_MUTEX_INITIALIZER;
    sigset_t old_set;
    sigset_t new_set;
    
    sigemptyset( &new_set );
    sigaddset( &new_set, SIGINT );
    
    pthread_mutex_lock( &mask_mutex );
    
    pthread_sigmask( SIG_BLOCK, &new_mask, &old_mask );
    
    func();
    
    pthread_sigmask( SIG_SETMASK, &old_mask, NULL );
    
    pthread_mutex_unlock( &mask_mutex );
    

    With no lock around the pthread_sigmask(), threads are likely to corrupt the process sigmask as execution overlaps.

提交回复
热议问题