Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Would something like this be satisfactory? It still isn't safe to unsubscribe an observer while being notified though, for that you would need an interface like you mentioned (as far as I can tell).</p> <pre><code>Subscribe(Observer *x) { mutex.lock(); // add x to the list mutex.unlock(); } Unsubscribe(Observer *x) { mutex.lock(); while (!ok_to_delete) cond.wait(mutex); // remove x from list mutex.unlock(); } NotifyLoop() { while (true) { // wait for something to trigger a notify mutex.lock(); ok_to_delete = false; // build a list of observers to notify mutex.unlock(); // notify all observers from the list saved earlier mutex.lock(); ok_to_delete = true; cond.notify_all(); mutex.unlock(); } } </code></pre> <p>If you want to be able to Unsubscribe() inside Notify() - <em>(a bad design decision on the client IMO...)</em> you can add the thread id of the notifier thread into your data structure. In the Unsubscribe function you can check that thread id against the current thread's id (most threading libraries provide this - eg. pthread_self). If they are the same, you can proceed without waiting on the condition variable.</p> <p>NOTE: If the client is responsible for deleting the observer, this means you run into the situation where inside the Notify callback, you will have unsubscribed and deleted the observer, but are still executing something with that junked this pointer. It is something the client will have to be aware of and to only delete it at the end of the Notify().</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.
    1. VO
      singulars
      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