简体   繁体   中英

Why locally created struct can't be send to another thread?

why in DI can't send to another thread through Tid.send local instances of structs? I would like to make simple handling of thread communication like this:

void main()
{
    ...
    tid.send(Command.LOGIN, [ Variant("user"), Variant("hello1234") ] );
    ...
}

void thread()
{
    ...
    receive(
       (Command cmd, Variant[] args) { ... })
    )
    ...
}

If I understand it correctly, D should create the array of Variants in the stack and then copy content of the array the send function right? So there should not be any issues about synchronization and concurrency. I'm quiet confused, this concurrency is wierd, I'm used to code with threads in C# and C.

Also I'm confused about the shared keyword, and creating shared classes. Usualy when I try to call method of shared class instance from non-shared object, the compiler throws an error. Why?

you should idup the array and it will be able to go through, normal arrays are default sharable (as they have a shared mutable indirection)

as is the compiler can rewrite the sending as

Variant[] variants = [ Variant("user"), Variant("hello1234") ] ;
tid.send(Command.LOGIN, variants);

and Variant[] fails the hasUnsharedAlias test

you can fix this by making the array shared or immutable (and receiving the appropriate one on the other side)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM