关于使用 QThreadStorage 的线程安全
这是一个线程问题,我基本上开始使库线程安全。我的用例如下 -
struct <>
{
int thread_specific_value;
}
1)例如旋转 5 个线程。
2)每个线程进行操作,并将thread_specific_value存储在上述数据结构中。这是在每个线程初始化时动态分配的,并添加到 QThreadStorage 中。
3)一旦所有线程返回主线程,我喜欢访问所有线程的errno值并进行一些处理。在我从主线程中删除该线程之前,我是否可以获取其存储数据的信息并将其存储在主线程的特定存储中。
简而言之,如何迭代所有线程特定存储数据的 QThreadStorage 并从主线程进行一些处理?
This is a threading question where I basically started making a library thread-safe. My use-case is as follows -
struct <>
{
int thread_specific_value;
}
1) Spin 5 threads for example.
2) Each thread does operation and store thread_specific_value in the above data structure for example. This is dynamically allocated at the initialization of each thread and added to QThreadStorage.
3) Once all threads return to main thread, I like to access the errno values of all threads and do some processing. Before I delete the thread from the main thread, can I get the information of its storage data and store in main thread's specific storage.
In nutshell, how can I iterate through QThreadStorage of all the thread specific stored data and do some processing from main thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
存储在 QThreadStorage 中的数据只能从放置该数据的线程访问。时期。如果您想从其他线程访问相同的数据,则必须将其另外存储在其他地方。特别是,线程特定值在线程退出时被销毁;如果你想保留该值,请在线程退出之前将其保存在某个地方。
简而言之,不要尝试使用 QThreadStorage 进行线程间通信。这不是它存在的目的。
Data stored in QThreadStorage is accessible only from the thread that put it there. Period. If you want to access the same data from other threads, you must store it additionally elsewhere. In particular, the thread-specific value is destroyed on thread exit; if you want to keep the value, save it somewhere before the thread exits.
In short, don't try to use QThreadStorage for inter-thread communication. That's not what it's there for.
很抱歉回答一个已经解决了9年多的问题。我正在寻找像这样的类似问题的解决方案,我受到 @bdonlan 接受的答案中这句话的启发:
因此,您可以将唯一的副本存储在其他地方,而不是在其他地方存储副本,即主线程,收集容器中不同线程的所有副本(列表或映射,但不是 std::vector 或 QVector)。然后,在每个线程中,QThreadStorage 存储一个指向主线程中副本的指针。请注意,只要该副本仅由一个线程访问,那就是一样的。
当线程在主线程的容器中分配数据时,您仍然需要锁。但持续的访问不需要任何锁定。
最后,所有线程返回主线程,就可以无锁地访问容器了。
Sorry to reply on a question solved for over 9 years. I'm looking for a solution for a similar question like this one and I'm inspired by this sentence from the accepted answer by @bdonlan:
So, instead of storing a copy elsewhere, you could just store the only copy elsewhere, i.e. in the main thread, collect all copies for different threads in a container (list or a map, but not a std::vector or QVector). Then, in each thread, the QThreadStorage stores a pointer to the copy in the main thread. Note, as long as the copy only get accessed by one thread, it's the same.
When a thread allocates a the data in the main thread's container, you'll still need a lock. But ongoing access won't need any lock.
In the end, all threads returns to the main thread, you can access the container lock free.