On Wednesday, 28 January 2015 at 11:50:46 UTC, Danny wrote:
Hello,
I'm trying to write some toy examples using threads in D.
Is the std.stdio.File thread-local or shared? Is flockfile used
when I synchronize on it?
I tried checking phobos myself and found some things I don't
get (in stdio.d):
alias FLOCK = flockfile;
this(this) { @trusted
if(fps_)
FLOCK(fps_);
}
What is "this(this)"?
this(this) is the constructor syntax for construction of an
already
initialised struct. (sort of equivalent to the C++
class foo {
foo(const foo& other)
{
...
}
} )
used like
struct somestruct
{
...
this()
{
writeln("calling this()");
}
this(this)
{
writeln("calling this(this)");
}
}
...
auto foo = somestruct(); //prints calling this()
auto baz = foo; //prints calling this(this)
If I want to write to stdout from a thread, do I use
LockingTextWriter? File? shared File? Does each thread have the
same stdout?
Yes
Finally, I'm trying to come to grips with "shared":
What does specifying "shared class" or "shared struct" do?
all methods are marked as shared
(similar to what final class quux { ... } does compared to just
class quux { ... } )
The first use of shared is to signal to the compiler that it
should not store the variable in thread-local storage. But when
I acquire a lock (using "synchronized", say), I'm supposed to
cast away the "shared", right?
IIRC ,yes.
as in
class Bar { ... }
auto foo(shared Bar bar)
{
synchronized(bar) //acquire lock
{
Bar not_shared_bar = cast(Bar) bar;
...
//use not_shared_bar here as thread local.
// No races can occur because of the lock.
// DO NOT allow references to non_shared_bar to escape
// as using them outside the synchronised could lead to
racing
}
}
Does it then still know that it's not thread-local (but that I
ensured that nobody else accesses it for the time being)?
No. it's up to you to make sure that no non-shared references
escape