Input/Output multiple values from function

Simen Kjærås simen.kjaras at gmail.com
Thu Aug 29 09:04:17 UTC 2019


On Wednesday, 28 August 2019 at 13:11:46 UTC, Jabari Zakiya wrote:
> When I do this:
>
> uint a; uint b; uint[] c; uint[] d;
>   AliasSeq!(a, b, c, d) = genPGparameters(pg);
>   modpg    = a;
>   res_0    = b;
>   restwins = c;
>   resinvrs = d;
>
> the compiler (ldc2 1.17) says:
>
> D Projects ~/D/bin/ldc2 --release -O3 twinprimes_ssoznew1.d
> twinprimes_ssoznew1.d(170): Error: cannot implicitly convert 
> expression c of type uint[] to shared(uint[])
> twinprimes_ssoznew1.d(171): Error: cannot implicitly convert 
> expression d of type uint[] to shared(uint[])
>
> where modpg, res_0; restwins, resinvrs are shared (global) 
> variables.

Reduced example:

unittest {
     int[] a;
     // cannot implicitly convert expression a of type int[] to 
shared(int[])
     shared int[] b = a;
}

This is because an int[] is mutable and thread-local, while 
shared(int[]) is mutable and shared. Shared mutable data must be 
guarded closely, preferably behind a mutex or similar. Assigning 
the value of `a` to `b` above would leave a mutable reference to 
the shared data on a thread, and could easily lead to race 
conditions.

In order to fix this issue, consider several things:

Do modpg and friends really need to be shared? Removing shared() 
from them will still make them available to other parts of your 
code, but they will be thread-local instead. If you're not doing 
threaded work, that should be perfectly fine.

Can they be immutable? If they're initialized once and never 
changed, this could be a good solution.

If they need to be shared and mutable, have you protected them 
enough from race conditions? Are there possible situations where 
other threads may be accessing them while one thread is writing 
to them?

Multi-threaded programming is hard, and requires a lot more 
knowledge than we have about your project from the code you've 
posted, so only you can answer these questions. If you're unsure, 
you can probably just remove shared() from modpg and friends.

--
   Simen


More information about the Digitalmars-d-learn mailing list