Reputation: 11
For example:
pthread_mutex_lock();
//Do something
sleep(1); //causes issues waiting while holding lock
pthread_mutex_unlock();
what is the solution if we don't want to use sleep inside mutex lock
Upvotes: 0
Views: 3703
Reputation: 1
As a rule of thumb, you usually (but not always) don't want to hold a mutex for a long period of time (otherwise, other threads locking the same mutex would wait too long), and a full second is a long period for a processor doing billions of elementary operations each second.
You might want to use condition variables (since pthread_cond_wait is atomically releasing the mutex), or do the sleep
(or some poll(2)...) outside of the locked region. You might even -on Linux- use pipe(7)-s -or the cheaper but Linux-specific eventfd(2)- to communicate between threads running event loops.
The coverity static source analyzer is heuristic and might give false alarms.
Take time to read a good Pthread tutorial.
Upvotes: 7