Note that there are some explanatory texts on larger screens.

plurals
  1. POmutex attribute PTHREAD_PROCESS_SHARED inverts logic?
    text
    copied!<p>This is a follow-on to my previous question (<a href="https://stackoverflow.com/questions/17720048/pthread-mutex-unlocking-over-different-threads">pthread mutex (un)locking over different threads</a>). I got puzzled by how to handle questions and answers here, so I give it a new try :o)</p> <p>I'm trying to handle mutex through processes and threads and using the mutex attribute PTHREAD_PROCESS_SHARED to arrange this. I'Ve added a small example (based on Paolo's example from my previoous post) which is demonstrating my problem:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stddef.h&gt; #include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;semaphore.h&gt; pthread_mutex_t m; sem_t s1, s2; void print(const char *s, int err) { printf("%s %d %s\n", s, err, strerror(err)); } void *start_t1(void *arg) { sem_wait(&amp;s1); // &lt;-t2 print("t1: unlock ", pthread_mutex_unlock(&amp;m)); sem_post(&amp;s2); //-&gt;t2 } void *start_t2(void *arg) { sem_wait(&amp;s2); // &lt;-main print("t2: lock ", pthread_mutex_lock(&amp;m)); sem_post(&amp;s1); // -&gt;t1 sem_wait(&amp;s2); // &lt;-t1 sem_post(&amp;s1); // -&gt;main } void main(void) { pthread_mutexattr_t mattr; pthread_mutexattr_init(&amp;mattr); pthread_mutexattr_settype(&amp;mattr, PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutexattr_setpshared(&amp;mattr, PTHREAD_PROCESS_SHARED); sem_init(&amp;s1, 0, 0); sem_init(&amp;s2, 0, 0); print("main init", pthread_mutex_init(&amp;m, &amp;mattr)); pthread_t t2, t1; pthread_create(&amp;t1, NULL, start_t1, NULL); pthread_create(&amp;t2, NULL, start_t2, NULL); sem_post(&amp;s2); // -&gt;t2 sem_wait(&amp;s1); // &lt;-t2 pthread_join(t1, NULL); pthread_join(t2, NULL); } </code></pre> <p>The output is:</p> <pre><code>main init 0 Success t2: lock 0 Success t1: unlock 1 Operation not permitted </code></pre> <p>T1 is not permitted to unlock the mutex initialized in main and locked by T2. Which is not what I expect! T1 should be allowed to unlock the mutex because of type <code>PTHREAD_PROCESS_SHARED</code>. Am I wrong ?</p> <p>If the mutex initialization is changed to using default attributes (<code>pthread_mutex_init(&amp;m, **NULL**)</code>), then it's working.</p> <pre><code>main init 0 Success t2: lock 0 Success t1: unlock 0 Success </code></pre> <p>Seems to be some kind of inverted logic !</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload