简体   繁体   English

特定于线程的数据 - 为什么我不能只使用带有线程ID的静态映射?

[英]Thread-specific data - why can't I just use a static map with thread IDs?

While reading up on POSIX threading, I came across an example of thread-specific-data. 在阅读POSIX线程时,我遇到了一个特定于线程的数据示例。 I did have one area of confusion in my mind... 我脑子里确实有一个混乱的地方......

The thread-specific-data interface looks a little clunky, especially once you mix in having to use pthread_once, the various initializers, etc. 线程特定数据接口看起来有点笨拙,特别是一旦你混合使用pthread_once,各种初始化器等。

Is there any reason I can't just use a static std::map where the key is the pthread_self() id and the data value is held in the second part of the std::pair? 有什么理由我不能只使用静态std :: map,其中键是pthread_self()id,数据值是否保存在std :: pair的第二部分?

I can't think of a reason that this wouldn't work as long as it was wrapped in a mutex, but I see no suggestion of it or anything similar which confuses me given it sounds much easier than the provided API. 我想不出这样的原因,只要它被包含在互斥锁中就不会起作用,但是我没有看到它或类似的任何混淆我的建议,因为它听起来比提供的API容易得多。 I know threading can have alot of catch-22's so I thought I'd ask and see if I was about to step in... something unpleasant? 我知道线程可以有很多捕获22,所以我想我会问,看看我是否准备介入......一些不愉快的事情? :) :)

I can't think of a reason that this wouldn't work as long as it was wrapped in a mutex 我想不出这样一个原因,只要它被包含在互斥锁中就不会起作用

That in itself is a very good reason; 这本身就是一个很好的理由; implemented properly, you can access your thread-specific data without preventing other threads from simultaneously creating or accessing theirs. 如果实施得当,您可以访问特定于线程的数据, 而不会阻止其他线程同时创建或访问它们。

There's also general efficiency (constant time access, versus logarithmic time if you use std::map ), no guarantee that pthread_t has a suitable ordering defined, and automatic cleanup along with all the other thread resources. 还有一般的效率(恒定时间访问,相对于对数时间,如果你使用std::map ),不保证pthread_t有一个合适的排序定义,并自动清理以及所有其他线程资源。

You could use C++11's thread_local keyword, or boost::thread_specific_ptr , if you don't like the Posix API. 如果您不喜欢Posix API,可以使用C ++ 11的thread_local关键字或boost::thread_specific_ptr

  1. pthread thread-specific-data existed before the standard library containers pthread特定于线程的数据存在于标准库容器之前
  2. thread-specific-data avoids the need of locking and makes sure no other thread messes with the data 特定于线程的数据避免了锁定的需要,并确保没有其他线程与数据混淆
  3. The data is cleaned up automatically when the thread disappears 当线程消失时,数据会自动清理

Having said that, nothing stops you from using your own solution. 话虽如此,没有什么能阻止您使用自己的解决方案。 If you can be sure that the container is completely constructed before any threads are running (static threading model), you don't even need the mutex. 如果您可以确定在任何线程运行之前完全构造容器(静态线程模型),您甚至不需要互斥锁。

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

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