pthreads - Permanent mutex locking causing deadlock? -


itemprop = "text">

I'm having a problem with mutex (pthread_mutex on Linux), where a thread re-muted it after unlocking it Locks X, the second thread is not very successful in getting a lock. I have attached a test code where a mute x has been made, with two threads, which locks the mute x in the endless loop, for a while Sleeps and unlocks it for Land.

The output which I expect to see is "alive" messages from both threads, one for each (for example 121212121212). But what do I get that threads get most of the locks (for example 111111222222222111111111 or just 1111111111111 ...).

If I add a sleep 1) After opening the lock, everything works as expected. Apparently when the thread goes to sleep then the other thread gets its lock - though this is not the way I was hoping, as the second thread has already said pthread_mutex_lock. I suspect this is the way it is implemented, that is the priority of thread, but some problems arise in this special test. Is there any way to stop it (by deliberately adding a delay or adding some kind of signal) or where is my error in understanding?

  #include & lt; Pthread.h & gt; #include & lt; Stdio.h & gt; #include & lt; String.h & gt; # Include & lt; Sys / time.h & gt; # Include & lt; Unistd.h & gt; Pthread_mutex_t mutex; Zero * Thread Function (Zero * Id) {int count = 0; While (true) {pthread_mutex_lock (& ​​amp; mutex); Usleep (50 * 1000); Pthread_mutex_unlock (& ​​amp; amp; mutex); // sleep (1); ++ count; If (calculation% 10 == 0) {printf ("thread% d alive \ n", * (int *) ID); Calculation = 0; }} Return 0; } Int main () {// Create a Mute X pthread_mutexattr_t attr; Pthread_mutexattr_init (& amp; attr); Pthread_mutex_init (& amp; mutex, & amp; ethernet); // Create two threads pthread_t thread1; Pthread_t thread 2; Pthread_attr_t attributes; Pthread_attr_init (& amp; Properties); Int id1 = 1, id2 = 2; Pthread_create (& thread1, & amp; Features, and Thread Function, & amp; id1); Pthread_create (& thread2, & attributes, and thread function, & amp; id2); Pthread_attr_destroy (& amp; Properties); Sleep (1000); Return 0; Incorrectly understand the way you do the mutuses (at least in your special implementation).  

Generally, threads continue as long as they do not have to wait for resources or they use their quantity (time slice).

Where there is no resource dispute and all the threads have the same priority, the best determining algorithm is to slice each one of the same time before swapping. The reason for this is that swap operation takes some time, so you do not want to do this often (relative to the real work being done by thread.)

If you want to make alternate between threads You are more determined than Mute X, such as the set of condition variables:


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -