Igor
Igor

Reputation: 281

How to share data between threads?

In the main thread I open a new thread that gets the number of new messages of user (takes about 5 secs) and this second thread should save the number in some place.

In the main thread I should check the "some place" and if the value exists I display it on the page.

Where can I save the value from the second thread to read it from the main one? This value is unique per user so I can't use static field.

Thank you for advance!

Upvotes: 1

Views: 801

Answers (3)

Istvan
Istvan

Reputation: 399

The way I do it, i have a vector od "ThreadData" elements. Each started thread gets this element when started and it can update that data (protected by mutexes). The main thread simply checks some flag in the element (ThreadState -- Running, Idle, Stopped, etc) and read the other data which the thread updated.

Upvotes: 0

alxx
alxx

Reputation: 9897

You can use static dictionary with user id as key and result as value. Protect dictionary access with locks. After main thread reads value, you can clear it from dictionary.

Upvotes: 1

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 30003

Use critical section to protect access to some data when several threads can read/write it. Use singleton instance to store data, global variable, registry pattern or whatever.

Upvotes: 1

Related Questions