views:

180

answers:

4

Hi!

let's say i have a singleton object with a static function:

static int MySingletonObject::getInt()

now i would like to return a different int depending on which workingthread (MFC threading) is calling the function.

I know that i can pass parameters to the threadingfunction when creating the thread. But Is there a way to identify the thread without info from those parameters?

Thanks!

+1  A: 

call GetCurrentThreadId (on a windows machine) it will return the thread id in which context the calling function is running

Alon
A: 

You can call GetCurrentThreadId() - will return an integer identifier - or GetCurrentThread() - will return a handle which can be cast to an integer identifier - from any thread - those values will be unique for any thread within the process.

sharptooth
how expensive is such a call? I intend to use it in some smartpointer implementation and it would be called upon each dereferencing of the smartpointer
Mat
Quite expensive. 100 million calls in a loop execute in 235 milliseconds on my machine. I guess it will be the same on any reasonably modern machine. So this can be a problem if you call this function very often.
sharptooth
that's cant be right!, windows keeps this information in a memory structure http://en.wikipedia.org/wiki/Win32_Thread_Information_Block so it should be as expensive as getting integer value from memory (which should be very cheap)
Eli
That data is managed by Windows and retrieving it requires an API call and API calls are relatively expensive. Maybe that "can't be right", but there's no reasonable way of finding out how expensive some code is to run other than to run it and time its execution.
sharptooth
according to this wiki page, the TIB is directly accessible. how would I retrieve the thread index that way? my asm isn't good :/
Mat
managed to access it. tested performance myself: 1'000'000'000 iterations in Debug mode -> empty(just incrementing i): 2100 ms, using GetCurrentThreadId: 3954 ms, accessing it directly by pointer: 1650 ms (someone explain me why this is even faster than the empty loop O_o')
Mat
That can be faster for whatever reason. Debug version can include various checks that introduce significant overhead. You should only compile with optimizations on for measurements.
sharptooth
+3  A: 

What you want is Thread Local Storage. Have a read of this for Windows implementation of TLS: http://msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx

Igor Zevaka
A: 

Really sounds like you are looking for thread local storage as Igor suggests - I would choose to use the boost.Thread code (documentation here) because:

  • cross platform / compiler
  • generally useful and convinient for this kind of task

    (actually I wonder if you are actually trying to create something quite a lot like a boost::thread_specific_ptr given what you said about your needs)

Elemental