Subj : Re: pthread_mutex_trylock problem To : comp.programming.threads From : David Schwartz Date : Wed Aug 31 2005 11:17 am wrote in message news:1125489761.189542.167460@g49g2000cwa.googlegroups.com... >I would like to know if one thread acquires a lock(by using > pthread_mutex_lock) and another thread tries to acquire it it would > sleep on it and once the thread which acquired releases it the first > thread which is sleeping acquires. > When would we use pthread_mutex_trylock() then? What is the use of such > a function. It's sometimes useful in very rare cases where you cannot wait for a lock, but can do something very efficiently if you can get the lock immediately. For example, consider a server where each client is protected by a lock. Threads that are handling a client hold the lock on that client, and they might hold it for awhile if that client is doing a lot of work. One thread, handling an administrative client, receives a command to disconnect another client. If it can get that client's lock immediately, then it can shut the client down very quickly. But it can't afford to wait for that client's lock to be released if the client is in the middle of something complicated (because that would stall the administrative client for too long). It's also good in cases where there's potential deadlock. Imagine if you called 'pthread_mutex_lock' and two administrative clients each tried to disconnect the other. If you used 'pthread_mutex_lock', each client could hold a lock on itself and try to get a lock on the other. Very bad. With 'pthread_mutex_trylock', you can try to acquire the lock safely and do things the easy way. If you fail to get the lock, you can fall back to assigning another thread (which would hold no locks) to do the disconnection, and it can wait for the busy client to finish and the lock to be released. DS .