How to identify Threads or Routines?

They just print themselves as a Routine or a Thread. Looking at the Thread class code, there’s not even an id for a Thread. So, how can I identify them; is there a way to print their address?

Ok, apparently with hash at least.

thisThread.hash.postln
forkIfNeeded { thisThread.hash.postln }
forkIfNeeded { thisThread.parent.hash.postln }

// also
nil.hash // works

If one has a nicer way, meaning some actual thread ids, even in SC’s own conception thereof, let me know.

A Routine is a Thread, I think the only instance of Thread as such is the interpreter’s main process main thread, Threads are not OS threads as explained in the docs.

thisProcess.mainThread; // a Thread
thisProcess.mainThread.class; // Thread
thisThread.class === Thread; // ture
r { (thisThread.class === Routine).postln; }.play ; // true

Edit, the question was edited, yes, hash seems the only way to do that.

That would probably work – “probably,” because (as James McCartney has been quick to point out in the past when the subject of hashes came up) a hash is not guaranteed to to be unique per object. Hashes are designed to minimize collisions between “near” data: 1.0.hash and 2.0.hash should (and do) produce very distant ints, but when calculating a 32-bit hash for a 64-bit float, it’s certain that there are other float values that will have the same hash as 1.0 (and, intentionally, it should be hard to find one of those).

For a Routine, it’s hashing the memory address: 64 bits.

static int hashPtr(void* ptr) {
    int32 hashed_part = int32((size_t)ptr & 0xffffffff);
    return Hash(hashed_part);
}

I.e., take the lowest 32 bits of the address and hash. In theory you could have another Routine (or other object) living exactly 0x100000000 bytes away and the hash would be the same. This is practically impossible, so it’s not a terrible way to go.

It’s never come up in the 19 years I’ve been involved with SC. I can see some potential use for debugging, sure, but we also don’t want to weigh Thread down with more instance variables (it’s already quite large, in terms of memory slots).

hjh