Concurrency in D

Nathan M. Swan nathanmswan at gmail.com
Wed Jun 27 16:41:26 PDT 2012


On Wednesday, 27 June 2012 at 22:34:51 UTC, Minas Mina wrote:
> I have been "playing" latetly with std.concurrency and 
> core.thread. I like both, but they are entirely different 
> approaches to concurrency.
>

Aren't they great? ;)

> std.concurrency: Uses message passing. Does not allow passing 
> of mutable types.
> core.thread: Essentially the same as the approach taken by Java.
>
> 1) Is one favoured over the other? I guess std.concurrency 
> would be, because it uses messages (and I recently read 
> somewhere that immutability + message passing = good thing).

Personally I favor std.concurrency, in many cases I find it 
faster.

> Well, my problem about is, how can send mutable data to another 
> thread? _Can_ I do it? If not, how am I supposed to share data 
> between them? Not everything can be immutable right?

Mutable value types can be sent easily, because they are copied. 
You share data with shared(T) types, e.g. shared(Object) or 
shared(int[]).

However, I try to avoid shared data by keeping it in single 
threads, and having other threads access parts with message 
passing.

One paradigm is to isolate data into "thread objects," threads 
which have non-shared data on the stack, and have other threads 
send GetData messages and get ReturnedData messages.

> For example I would like to have a thread calculate the sum of 
> the first half of an array while another thread would calculate 
> the other half, and I could add the two results at the end.
>

Check out this:
http://dpaste.dzfl.pl/0f7ccb79

Note that for algorithms like this, you should check out 
std.parallelism, it's more high-level than std.concurrency.

> 2) What about core.thread? To do proper sync between threads in 
> core.thread, semaphore, mutexes and stuff like that are needed. 
> Are those "good practice" in D?
>

Part of D's philosophy is "you can get low-level and dirty if you 
want, but the easy/safe way should also be the fast way." 
core.thread is there for you, but std.concurrency is easier. Note 
that std.concurrency is written on top of core.thread.

I definitely prefer std.concurrency, but I don't write 
CPU-intensive stuff anyway, so I'm no expert.

> 3) I have also read a bit about syncronized classes and shared 
> classes/structs, altough I didn't understand it too much (well 
> I didn't try too much to be honest).
>

Objects of a synchronized class automatically lock/unlock every 
method call.

You don't share stack structs, though maybe shared(StructType)*.

> For all those appoaches, which is the preffered?
> For all those appoaches, which is the preffered for game 
> programming?
>
> Thank you.

Hope I've helped.
NMS


More information about the Digitalmars-d-learn mailing list