Mat
Mat

Reputation: 11883

c++ identify current thread in function?

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!

Upvotes: 1

Views: 14224

Answers (4)

sharptooth
sharptooth

Reputation: 170509

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.

Upvotes: 5

Elemental
Elemental

Reputation: 7521

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)

Upvotes: 0

Igor Zevaka
Igor Zevaka

Reputation: 76550

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

Upvotes: 3

Alon
Alon

Reputation: 4952

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

Upvotes: 2

Related Questions