Kartlee
Kartlee

Reputation: 1179

About thread-safety using 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?

Upvotes: 0

Views: 1981

Answers (2)

ZHANG Zikai
ZHANG Zikai

Reputation: 598

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:

If you want to access the same data from other threads, you must store it additionally elsewhere.

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.

Upvotes: 0

bdonlan
bdonlan

Reputation: 231383

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.

Upvotes: 3

Related Questions