Mutex takes a long time to unlock

I have two threads. The first one is something like this:

while(1) { pthread_mutex_lock(&mutex); //DO WORK pthread_mutex_unlock(&mutex); pthread_yield(); } 

The second blocks mutexes on a user event, changes some settings and unlocks. The thread is one ~ 200 iterations per second. However, sometimes it is necessary to activate the second stream up to 3 seconds (mutex lock). How to provide a quick 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 issue ("unlock mutex" → "to lock mutex").

+4
source share
3 answers

Try changing pthread_yield() to usleep(10) or usleep(100) to determine if your crop is causing problems, as I have seen cases where profitability does nothing, which will cause your loop to be unlocked and restart too fast for the first thread to catch it blocking most of the time. Then you might consider looking at state variables in pthread if you want more control.

+1
source

I am always worried when I see pthread_yield , it is non-standard according to the man page , so I generally avoid it, it really does not give you any guarantees anyway, it will put you in the execution queue, but that does not mean that there is anything else will start depending on how the OS prioritizes your thread.

what you might want to do explicitly transfers control to another thread using the signal and wait variable variables

+1
source

You have a bad design. A thread must contain a mutex only when it needs to access shared data structures. This should be a small fraction of the execution time of the thread, not the vast majority of them. If you see the type of template that you are developing, the time has come to redesign.

One possible pattern is for a compute thread to hold a pointer to global data during operation without saving the mutex. The user interface thread can then create a new version of the global data based on user interface input, and then publish a pointer to the new data so that the compute thread sees it the next time it leaves to get the pointer. Thus, the computation flow only needs to hold the mutex for as long as it takes it to copy the pointer.

Here's a simplified layout for the calculation flow:

 pthread_mutex_lock(&mutex); my_pointer = shared_pointer; pthread_mutex_unlock(&mutex); do_calculations(); 

And for the user interface thread, the logic is as follows: you are modifying a copy of the data. You create a new copy of the data. You get a mutex. You change shared_pointer to point to one of two copies of the data. You save another copy for change in the next pass.

+1
source

Source: https://habr.com/ru/post/1310182/


All Articles