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

前端 未结 6 1648
半阙折子戏
半阙折子戏 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:06

    As Glen noted, you get undefined behaviour if you attempt to unlock an unlocked mutex - don't try it. Debugging threads is hard enough without invoking undefined behaviour too.

    More importantly, the coding style is a little unusual - since you aren't going to do anything unless you get both locks, code accordingly:

    if (pthread_mutex_trylock(&crunch_mutex) == 0)
    {
        if (pthread_mutex_trylock(&queue_mutex) == 0)
        {
            printf("cr = %d, max = %d, cnt = %d\n",
                   crunching, max_crunching, queue_count(conn_queue));
            if (crunching < max_crunching && queue_count(conn_queue))
            {
                pthread_t tid;
                int rc = pthread_create(&tid, NULL,
                                   crunch_conn, (void *)queue_dequeue(conn_queue));
                if (rc != 0)
                {
                    // Error recovery
                    // Did you need what was returned by queue_dequeue()
                    // to requeue it, perhaps?
                }
                else
                {
                    crunching++;
                    // Do something with tid here?
                }
            }
            QUEUE_UNLOCK;
        }
        CRUNCH_UNLOCK;
    }
    

    This avoids the 'did I do it' variables; it is also instantly clear that as long as the unlock macros do what is expected (and there are no stray exceptions or setjmps around), that the mutexes that are locked are unlocked. It also avoids wasting energy on locking the queue mutex when the crunch mutex isn't available - but that's a minor issue compared to the added clarity.

提交回复
热议问题