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

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

    You don't need to do it that way. Try this:

        // This chunk of code makes dual locking semi-autonomous.
    int c_lckd = 0, q_lckd = 0;
    if (pthread_mutex_trylock(&crunch_mutex) == 0) c_lckd = 1;
    if (pthread_mutex_trylock(&queue_mutex) == 0) q_lckd = 1;
    
    if (c_lckd && q_lckd) {
      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 =
          pthread_create(
            &tid,
            NULL,
            crunch_conn,
            (void *)queue_dequeue(conn_queue)
          );
        crunching++;
      }
    
    }
    
    if (q_lckd) { QUEUE_UNLOCK; q_lckd = 0; }
    if (c_lckd) { CRUNCH_UNLOCK; c_lckd = 0; }
    

    It's a little easier to follow and doesn't risk trying to unlock an unlocked mutex.

提交回复
热议问题