getTid wrapper

Stanislav Blinov stanislav.blinov at gmail.com
Tue Mar 4 08:27:28 PST 2014


On Tuesday, 4 March 2014 at 15:52:37 UTC, Timothee Cour wrote:

> quoting from there:
> "The type of thisTid is Tid, but its value has no significance 
> for the
> program. Further, both threads report it to be surprisingly at 
> the same
> address:
> Owner : Tid(std.concurrency.MessageBox), address: 809C360
> Worker: Tid(std.concurrency.MessageBox), address: 809C360"

That part talks about thisTid, not Thread.getThis. Perhaps that 
book section is indeed not clear enough. &thisTid actually gets 
an address of 'thisTid', which is (at least in current 
implementation) a function.

> Likewise with writeln(&Thread.getThis);

Same as above. So you're printing function pointers, which are of 
course the same for every thread.

> How would I print a number/string that uniquely identifies a 
> thread?
> Tid is an opaque type, writeln(thisTid) isn't of any use.

If you want to print it, you can do so like this:

writefln("%s", cast(void*)Thread.getThis);

That is, you cast a reference returned by Thread.getThis() to a 
void* (a reference is a glorified pointer, after all). If you 
want to print something more meaningful, you can utilize the 
'name' property of Thread.

For simple identification purposes (i.e. when you want to check 
if the calling thread is the one you need), both thisTid and 
Thread.getThis can be used:

if (thisTid == expectedTid) { ... }

if (Thread.getThis is expectedThread) { ... }

If you don't feel like printing addresses or using name(), you 
can even build your own id system, i.e. like this:

-->8--

module threadid;

import core.atomic;

private shared uint lastID; // shared
private uint thisID;        // TLS

static this() { thisID = atomicOp!"+="(lastID, 1); }

@property uint threadID() { return thisID; }

--8<--

...or something to that extent. Now every thread that you ever 
create will get an ID number (from 0 to uint.max, be careful 
though if your app creates more than uint.max threads :o) ), 
which can be queried at any time:

import threadid;

//...

writeln(threadID);


More information about the Digitalmars-d-learn mailing list