简体   繁体   English

winapi:线程结束时获取回调

[英]winapi: get callback when thread ends

I have some c++ library code that creates some book-keeping data per thread that accesses it (based on thread-id).我有一些 C++ 库代码,可以为每个访问它的线程创建一些簿记数据(基于线程 ID)。 I would like to cleanup that data when a thread ends.我想在线程结束时清除该数据。 Is there a way (if not portable, then using win-api) to get notified when a thread ends?有没有办法(如果不可移植,则使用 win-api)在线程结束时得到通知?

// simplified example: // 简化示例:

std::mutex mutex_;
std::unordered_map<std::thread::id, int> thread_accesses_;

void LibFunction() {
  std::thread::id thread_id = std::this_thread::get_id();
  mutex_.lock();
  std::unordered_map<std::thread::id, int>::const_iterator it = thread_accesses_.find(thread_id);
  if(it == thread_accesses_.end()) {
    thread_accesses_[thread_id] = 0;
  } else {
    thread_accesses_[thread_id]++;
  }
  mutex_.unlock();
}

Thread-local storage is both C++ standard way and platform way.线程本地存储既是C++标准方式,也是平台方式。

C++ has thread_local keyword to declare thread-local variable. C++ 有thread_local关键字来声明线程局部变量。 Then destructor of that variable is called for each thread for which it was constructed.然后为每个为其构造变量的线程调用该变量的析构函数。 Thread local variable is constructed for at least all threads that access the variable, and possibly for other threads.线程局部变量至少是为访问该变量的所有线程构建的,也可能为其他线程构建。

Windows has thread-local storage as system mechanism. Windows 具有线程本地存储作为系统机制。 thread_local is implemented via this mechanism. thread_local就是通过这种机制实现的。

It is possible to have thread exit callbacks in Windows by other means:可以通过其他方式在 Windows 中进行线程退出回调:

  • having thread-local data and TLS callbacks in module by other means通过其他方式在模块中具有线程本地数据和 TLS 回调
  • Using DllMain callbacks使用 DllMain 回调
  • Passing FlsCallback in FlsAlloc , fiber local storage is something superior to thread local storage, and in absence of fibers it behaves exactly like thread local storageFlsAlloc传递FlsCallback ,纤程本地存储优于线程本地存储,并且在没有纤程的情况下,它的行为与线程本地存储完全相同

If cannot use thread_local , but want something simple and portable, consider also boost::thread_specific_ptr .如果不能使用thread_local ,但想要一些简单和便携的东西,也boost::thread_specific_ptr考虑boost::thread_specific_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM