Check to see if a pthread mutex is locked or unlocked (After a thread has locked itself)

后端 未结 3 1708
孤城傲影
孤城傲影 2020-11-29 06:54

I need to see if a mutex is locked or unlocked in an if statement so I check it like this...

if(mutex[id] != 2){
    /* do stuff */
}

but w

3条回答
  •  情书的邮戳
    2020-11-29 07:16

    Mutexes are not the right primitive for the scheme that you want to implement. You should be using condition variables:

    int run_thread_a = 0;
    pthread_mutex_t run_lock_a = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t run_cond_a = PTHREAD_COND_INITIALIZER;
    
    int run_thread_b = 0;
    pthread_mutex_t run_lock_b = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t run_cond_b = PTHREAD_COND_INITIALIZER;
    
    /* thread A */
    while (1) {
        /* Wait for Thread A to be runnable */
        pthread_mutex_lock(&run_lock_a);
        while (!run_thread_a)
            pthread_cond_wait(&run_cond_a, &run_lock_a);
        run_thread_a = 0;
        pthread_mutex_unlock(&run_lock_a);
    
        /* Do some work */
    
        /* Now wake thread B */
        pthread_mutex_lock(&run_lock_b);
        run_thread_b = 1;
        pthread_cond_signal(&run_cond_b);
        pthread_mutex_unlock(&run_lock_b);
    }
    
    /* thread B */
    while (1) {
        /* Wait for Thread B to be runnable */
        pthread_mutex_lock(&run_lock_b);
        while (!run_thread_b)
            pthread_cond_wait(&run_cond_b, &run_lock_b);
        run_thread_b = 0;
        pthread_mutex_unlock(&run_lock_b);
    
        /* Do some work */
    
        /* Now wake thread A */
        pthread_mutex_lock(&run_lock_a);
        run_thread_a = 1;
        pthread_cond_signal(&run_cond_a);
        pthread_mutex_unlock(&run_lock_a);
    }
    

    Each thread will block in pthread_cond_wait() until the other thread signals it to wake up. This will not deadlock.

    It can easily be extended to many threads, by allocating one int, pthread_cond_t and pthread_mutex_t per thread.

提交回复
热议问题