How to correctly destroy pthread mutex

后端 未结 4 686
天命终不由人
天命终不由人 2021-02-09 05:26

How exactly i can destroy a pthread mutex variable ?

Here is what i want to do. I want to have objects (structure variables) cached , which are looked up by key. I want

4条回答
  •  醉梦人生
    2021-02-09 05:57

    It's undefined behavior to (a) attempt to destroy a locked mutex, or (b) reference a destroyed mutex other than to call pthread_mutex_init to recreate it (See documentation). That means that the thread that destroys your shared mutex is going to race with the others locking it, and either (1) destroy happens first, other threads invoke undefined behavior trying to lock because of (b) or (2) lock in another thread happens first and destroying thread invokes undefined behavior because of (a).

    You need to change your design so that a mutex under active contention is never destroyed. For your example, you could destroy the shared mutex in main after all threads are joined. For the program you describe, you probably need to insert a reference count in the objects.

提交回复
热议问题