std.concurrent Tid vector initialization problem
Charles Hixson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jun 30 12:19:42 PDT 2015
On Sunday, 28 June 2015 at 09:59:29 UTC, Marc Schütz wrote:
> On Sunday, 28 June 2015 at 01:02:02 UTC, Charles Hixson wrote:
>> I'm planning an application where a series of threads each
>> ...gn. Does anyone have a better idea?
>>
>> (The rough estimate of the number of Tids is six, but that's
>> likely to change from run to run.)
>
> The most elegant solution I can think of is this:
>
> struct Go { }
>
> __gshared const Tid[] allTids;
>
> void myfunc(...) {
> receiveOnly!Go();
> // do the work
> }
>
> shared static this() {
> Tid[] tids;
> foreach(thread; threads)
> tids ~= spawn(&myfunc, ...);
> *cast(const(int)[]*) &allTids = tids;
> foreach(tid; allTids)
> tid.send(Go());
> }
>
> I believe the cast is not even undefined behaviour, because
> it's not immutable, but I'm not sure. But the const-ness guards
> against accidental modification of `allTids` by a thread.
>
> Alternatively, you could make `allTids` private, provide a
> public getter, and implement the threads in another module.
>
> Or you could simply leave the global array mutable and be
> careful not to modify it.
Thanks. That sounds similar to the approach that I had though
of, except that you're doing it in a static this().
(I'd have answered sooner, but my D email seems to have died.
Only the D groups are currently dead now, though my entire
account was dead for a couple of weeks. [AT&T])
More information about the Digitalmars-d-learn
mailing list