handling shared objects

Alex sascha.orlov at gmail.com
Mon Nov 26 14:00:14 UTC 2018


Hi all!
Can somebody explain to me, why the example below is not working 
in a way I'm expecting it to work?

My example is a little bit longer this time, however the half of 
it is taken from
https://dlang.org/library/std/concurrency/receive_only.html

´´´
import std.experimental.all;

struct D
{
	size_t d;
	static S s;
}
struct S
{
	D[] data;
}

struct Model
{
	auto ref s()
	{
		return D.s;
	}

	void run()
	{
		"I'm running".writeln;
		writeln(s.data.length);
	}
}

Model m;

void main()
{
	
	D.s.data.length = 4;
	m.run; //4

	auto childTid = spawn(&runner, thisTid);
	send(childTid, 0);
	receiveOnly!bool;
}

static void runner(Tid ownerTid)
{
	receive((size_t dummy){
		import core.thread : Thread;
				
		m.run;
         // Send a message back to the owner thread
         // indicating success.
         send(ownerTid, true);
     });
}
´´´

The idea is:
the model is something that I can declare deliberately in the 
application. And, I assumed that if it is (globally) shared, then 
so are all compartments of it, even if they are not explicitly 
part of the model.

Some problems arose:
1. Obviously, this is not the case, as the output is different, 
depending on the thread I start the model function.
2. If I declare the model object inside the main, the compiler 
aborts with the message "Aliases to mutable thread-local data not 
allowed."
3. If I mark the S instance as shared, it works. But I didn't 
intend to do this... Is this really how it meant to be?

As I'm writing the model object as well as all of its 
compartments, I can do almost everything... but what I to avoid 
is to declare the instances of compartments inside the model:
They are stored locally to their modules and the single elements 
of them have to know about the compound objects, like with the D 
and S structs shown.


More information about the Digitalmars-d-learn mailing list