You are not logged in.

#1 2010-08-13 03:08:49

Willem
Member
From: Wellington, NZ
Registered: 2009-10-09
Posts: 18

[SOLVED] pthreads and mutexes

Hi,

I have a process p1 which creates a thread t1.

The problem is this:

p1 creates t1 and a typical scenario is:
t1 calls pthread_mutex_lock.
p1 calls pthread_mutex_lock.
t1 call pthread_mutex_unlock
t1 calls pthread_mutex_lock ==> why did p1 not get the mutex as it was waiting for it?
t1 calls pthread_mutex_unlock

Eventually after a while, p1 does get the mutex, but it blocks for quite a while before getting the mutex, sometimes up to six seconds.
I would have expected that p1 would get an even chance at getting the mutex, but this does not happen.
It seems that t1 hogs the mutex.

As p1 created t1, they should have the same scheduling algorithm and priority.

The thread t1 does spin in a while loop, and if I put a usleep() in the loop, p1 gets a fair share of the mutex.

I unsuccessfully tried changing the priority of t1 to be a lower priority than p1, but the default linux scheduling policy SCHED_OTHER has a min and max value of 0.
Something like SCHED_BATCH would be better, but it seems that scheduling policy is not available.

I am a bit perplexed as to why p1 does not get an even shot at the mutex, as it is blocking waiting for the mutex to become available, but t1 just grabs it again.

Any thoughts or suggestions would be welcome

Thanks
Willem

Last edited by Willem (2010-08-15 00:53:09)

Offline

#2 2010-08-13 06:07:41

tavianator
Member
From: Waterloo, ON, Canada
Registered: 2007-08-21
Posts: 859
Website

Re: [SOLVED] pthreads and mutexes

Because t1 hasn't used up its timeslice yet.  Basically, when p1 fails to get the lock, it sleeps.  t1 has the lock, then releases it, then grabs it again.  p1 never gets a chance because t1 doesn't get context-switched out between the mutex grabs, since they occur very fast.  I'm guessing a sched_yeild() would have the same effect as usleep() here.  Eventually, t1 gets switched out (hopefully without holding the mutex), p1 wakes, and grabs the mutex.

Lesson: don't lock and unlock a mutex in a tight loop.

Offline

#3 2010-08-15 00:46:22

Willem
Member
From: Wellington, NZ
Registered: 2009-10-09
Posts: 18

Re: [SOLVED] pthreads and mutexes

Thank you for clearing it up, very informative.

Offline

Board footer

Powered by FluxBB