windows c ++识别函数中的当前线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1999049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:41:11  来源:igfitidea点击:

c++ identify current thread in function?

c++windowsmultithreadingmfc

提问by Mat

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.

现在我想根据调用函数的工作线程(MFC 线程)返回不同的 int。

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!

谢谢!

回答by sharptooth

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.

您可以调用GetCurrentThreadId()- 将返回一个整数标识符 - 或GetCurrentThread()- 将返回一个句柄,该句柄可以从任何线程转换为整数标识符 - 这些值对于进程中的任何线程都是唯一的。

回答by Igor Zevaka

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

你想要的是Thread Local Storage。阅读有关 TLS 的 Windows 实现的内容:http: //msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx

回答by Alon

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

调用GetCurrentThreadId(在 Windows 机器上)它将返回调用函数正在运行的上下文中的线程 ID

回答by Elemental

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:

听起来真的像 Igor 建议的那样寻找线程本地存储 - 我会选择使用 boost.Thread 代码(此处的文档),因为:

  • 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)

  • 跨平台/编译器
  • 对于此类任务通常有用且方便

    (实际上,我想知道您是否真的在尝试创建类似于 boost::thread_specific_ptr 的东西,考虑到您对您的需求所说的话)