Note that there are some explanatory texts on larger screens.

plurals
  1. POSleep while holding a boost::interprocess::scoped_lock causes it to be never released
    primarykey
    data
    text
    <p>I'm doing IPC on <strong>Linux</strong> using <code>boost::interprocess::shared_memory_object</code> as per <a href="http://www.boost.org/doc/libs/1_38_0/doc/html/interprocess/synchronization_mechanisms.html" rel="nofollow noreferrer">the reference</a> (anonymous mutex example).</p> <p>There's a server process, which creates the <code>shared_memory_object</code> and writes to it, while holding an <code>interprocess_mutex</code> wrapped in a <code>scoped_lock</code>; and a client process which prints whatever the other one has written - in this case, it's an <code>int</code>.</p> <p>I ran into a problem: if the server sleeps while holding the mutex, the client process is never able to aquire it and waits forever.</p> <p>Buggy <b>server</b> loop:</p> <pre><code>using namespace boost::interprocess; int n = 0; while (1) { std::cerr &lt;&lt; "acquiring mutex... "; { // "data" is a struct on the shared mem. and contains a mutex and an int scoped_lock&lt;interprocess_mutex&gt; lock(data-&gt;mutex); data-&gt;a = n++; std::cerr &lt;&lt; n &lt;&lt; std::endl; sleep(1); } // if this bracket is placed before "sleep", everything works } </code></pre> <p><b>Server</b> output:</p> <pre><code>acquiring mutex... 1 acquiring mutex... 2 acquiring mutex... 3 acquiring mutex... 4 </code></pre> <p><b>Client</b> loop:</p> <pre><code>while(1) { std::cerr &lt;&lt; "acquiring mutex... "; { scoped_lock&lt;interprocess_mutex&gt; lock(data-&gt;mutex); std::cerr &lt;&lt; data-&gt;a &lt;&lt; std::endl; } sleep(1); } </code></pre> <p><b>Client</b> output (waits forever):</p> <pre><code>acquiring mutex... </code></pre> <p>The thing is, if I move the bracket to the line before the <code>sleep</code> call, everything works. Why? I didn't think sleeping with a locked mutex would cause the mutex to be eternally locked.</p> <p>The only theory I have is that when the kernel wakes up the server process, the scope ends and the mutex is released, but the waiting process isn't given a chance to run. The server then re-acquires the lock... But that doesn't seem to make a lot of sense.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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