If you unlock an already unlocked mutex, is the behavior undefined?

前端 未结 6 1650
半阙折子戏
半阙折子戏 2020-12-29 03:10

If you unlock an already unlocked mutex, is the behavior unsafe, safe, or undefined?

The purpose of the question is related to the following code, where I don\'t kno

6条回答
  •  攒了一身酷
    2020-12-29 04:07

    Try it. This is code working correct.

    // Mutex is not busy
    if(pthread_mutex_trylock(&object->mtx) == 0) {
        if(pthread_mutex_unlock(&object->mtx)!=0) {
            perror("ERRN: pthread_mutex_unlock:");
        }
    }
    // Mutex is already busy
    else {
        if(pthread_mutex_unlock(&object->mtx)!=0) {
            perror("ERRN: pthread_mutex_unlock:");
        }
    }
    

    // In this point -- we correctly unlocked mutex.

    if(pthread_mutex_destroy(&object->mtx) != 0) {
        perror("ERRN: pthread_mutex_destroy:");
    }
    

提交回复
热议问题