Language idea - simple thread spawning
Artur Skawina
art.08.09 at gmail.com
Fri Feb 17 02:35:02 PST 2012
On 02/17/12 03:38, Jonathan Stephens wrote:
> I would like to get some feedback on a language feature I think would benefit D.
>
> The feature is simplified "lazy" thread blocks that would considerably
> simplify the process of spawning and running new threads.
> Multiprocessing is becoming a more-and-more important feature for
> programmers as Moore's Law pushes us into a greater number of
> processors with only marginal speed improvements.
>
> I think this feature could make it so much simpler to start and stop
> threads that many programmers that currently only multiprocess when
> necessary would, instead, do it any time they felt their software
> could benefit from it.
>
> Anyhow, here's an example of my idea:
>
> import std.stdio;
> import core.thread;
>
> void main() {
> runthread {
> Thread.sleep(dur!("msecs")(20));
> writeln("C");
> }
> threadA: runthread {
> Thread.sleep(dur!("msecs")(10));
> writeln("A");
> }
>
> sync threadA;
> writeln("B");
> sync;
> writeln("End");
> }
>
> For this example, the output would always be:
> A
> B
> C
> End
>
[...]
> What are your thoughts? From a high level, does this seem that it
> would beneficial? Would it be worth my time to implement this?
Would it really be an significant improvement? Compare the above with this:
-----------------------------------------------------
import std.stdio;
import core.thread;
void main() {
new thread({
Thread.sleep(dur!("msecs")(20));
writeln("C");
});
auto threadA = new thread({
Thread.sleep(dur!("msecs")(10));
writeln("A");
});
threadA.join();
writeln("B");
thread.sync();
writeln("End");
}
-----------------------------------------------------
which works right now [1].
artur
[1] with a trivial "thread" class like the one below. Note it's just POC,
you may not want to implement it like this. Oh, i used "thread" to keep the
diff to your example as small as possible, before someone mentions that it
must use CamelCasing. :^)
class thread: Thread {
static Thread[typeof(this)] threads;
this(void function() f) { auto t = super(f); threads[this] = t; t.start(); }
this(void delegate() f) { auto t = super(f); threads[this] = t; t.start(); }
void join() { super.join(); threads.remove(this); }
static sync() { foreach(t; threads) t.join(); }
}
More information about the Digitalmars-d
mailing list