Concurrency Confusion
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Aug 4 01:32:18 PDT 2015
On 08/04/2015 01:03 AM, "岩倉 澪" wrote:
> Hi all, I'm a bit confused today (as usual, haha).
>
> I have a pointer to a struct (let's call it Foo) allocated via a C library.
> I need to do some expensive computation with the Foo* to create a Bar[],
> but I would like to do that computation in the background, because the
> Bar[] is not needed right away.
>
> I definitely do not want there to be a copy of all elements of the Bar[]
> between threads, because it is very large.
>
> I tried to implement it like this:
>
> void fooPtrToBarArr(in shared Foo* f, out shared Bar[] b){ /*do
> work*/ }
> __gshared Foo* foo;
> foo = allocateFoo();
> __gshared Bar[] bar;
> spawn(foo, bar);
>
> To my dismay, it results in a cryptic compiler error:
>
>> template std.concurrency.spawn cannot deduce function from argument types
>> !()(void function(shared(const(Foo*)) f, out shared(Bar[]) b), Foo*,
>> Bar[]), candidates are:
>> /usr/include/dlang/dmd/std/concurrency.d(466):
>> std.concurrency.spawn(F, T...)(F fn, T args) if (isSpawnable!(F, T))
>
> Any help would be greatly appreciated :)
>
>
__gshared behaves like C globals and need not be passed to spawned
functions. (Although, if needed, they must be passed as shared and
casted back to non-shared in the thread function.)
The following seems to achieve what you describe:
import std.stdio;
import std.concurrency;
import core.thread;
struct Foo
{}
struct Bar
{
int i;
}
void fooPtrToBarArr()
{
bar ~= Bar(42);
}
__gshared Foo* foo;
__gshared Bar[] bar;
void main()
{
spawn(&fooPtrToBarArr);
thread_joinAll();
writeln(bar);
}
Ali
More information about the Digitalmars-d-learn
mailing list