Mutex takes a long while to unlock
I have two threads. First one is something like this:
while(1)
{
pthread_mutex_lock(&mutex);
//DO WORK
pthread_mutex_unlock(&mutex);
pthread_yield();
}
The second one locks the mutex on user event, change some settings and unlocks. Thread one does ~ 200 iterations a second. However on occasion it takes the second thread up to 3 seconds to get active (to lock the mutex). How do I ensure faster response?
EDIT- second thread:
while(1)
{
waitForUserInput(); // blocking call to linux input
pthread_mutex_lock(&mutex);
// Change some settings which are used by the first thread
pthread_mutex_unlock(&mutex);
}
EDIT2 - Fixed th开发者_JS百科e question ("to unlock the mutex" -> "to lock the mutex").
Try changing pthread_yield()
to usleep(10)
or usleep(100)
to determine if the yield is causing you problems, as I've seen cases where yield does nothing, which would cause your loop to unlock and relock a too quickly for the first thread to catch its lock most of the time. Then you might consider looking at condition variables in pthread if you want more control.
I'm always concerned when i see pthread_yield
it is non-standard according to the man page so I generally avoid it also it really gives you no guarantees anyway, it will put you at the back of the run queue but that doesn't mean that that anything else will run depending on how the OS prioritizes your thread.
what you might want to do is explicitly hand off control to the other thread using condition variables signal
and wait
Your design is bad. A thread should hold a mutex only while it needs to access shared data structures. That should be a small fraction of the thread's run time, not the vast majority of it. If you see the kind of pattern you have developing, it's time to redesign.
One possible pattern is to have the computing thread hold a pointer to the global data while it's running without holding the mutex. The UI thread can then create a new version of the global data based on the UI input and then publish the pointer to the new data so that the computing thread sees it the next time it goes to get the pointer. That way, the compute thread only has to hold the mutex as long as it takes it to copy a pointer.
Here's the oversimplified layout for the compute thread:
pthread_mutex_lock(&mutex);
my_pointer = shared_pointer;
pthread_mutex_unlock(&mutex);
do_calculations();
And for the UI thread, the logic goes like this: You modify a copy of the data. You make a new copy of the data. You acquire the mutex. You change shared_pointer
to point to one of the two copies of the data. You hold the other copy to modify on the next pass.
精彩评论