Issue calling methods using std.concurrency

Stanislav Blinov stanislav.blinov at gmail.com
Mon Apr 23 14:18:52 PDT 2012


On Monday, 23 April 2012 at 18:44:37 UTC, Casey wrote:
>
> I actually did print out the value being passed successfully.  
> It's just that when I used the queue methods (enqueue and 
> dequeue), it get this error.  The queue itself is shared, but 
> none of the methods are expecting a shared value nor do I 
> believe they should.
>

 From what I can gather from error messages, you have a shared 
reference to a non-shared class:

---

class Queue {
     void enqueue(int v) { /*...*/ }
     int dequeue() { /*...*/ }
}

// ...

auto queue = new shared(Queue);

// ...

---

If that is the case, then it's not that the methods are expecting 
a shared value, it's that methods are not 'expecting' a shared 
'this'. And indeed there is what seems to be a quirk in the 
design of 'shared' in that it won't allow such calls. But it is 
actually not a quirk, but means for the compiler to discard 
incorrect code. If you want your methods to be called for shared 
reference, the whole your class or at least those methods should 
be shared as well. Just like with const: if you have a const 
reference, you can only call const methods.

Whenever you encounter such issue, you should carefully think 
about what's going on. If the class you use is not designed to be 
shared, you shouldn't just start calling its methods from 
different threads, since it is by definition not safe, no matter 
what its documentation may state (remember, shared is there to 
enforce such guarantees). If it is actually made thread-safe 
(via, e.g. synchronized blocks), then the reference really 
shouldn't be shared.

All that said, your best bets are either to rethink your design 
(do you really need a shared queue if you are using message 
passing anyway?), or to provide an implementation for shared 
queue. If anything, consider that shared queue is very different 
from non-shared one: are you satisfied with locking queue, or do 
you need lockless one? Is your queue mostly read or written 
thread-wise, or maybe it's only one provider and one consumer? 
I'm sure experts in asynchronous programming can provide a dozen 
more questions that should be answered and then coded into the 
implementation of a queue that you want to share among threads.

I understand the desire to have one neat implementation that 
'just works', no matter the conditions, but unfortunately, with 
asynchronous programming that is not an option.


More information about the Digitalmars-d-learn mailing list