Click here to Skip to main content
15,917,968 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a "client process" runing in one thread , and more threads, that are accessing different data that are provided by "client process". I am considering making a "client process" as static class, so that data would be easily accessible by any thread (read only).
Do I have to use thread locking ? What would be the best practice to share (provide) data to another threads?
Posted

Oh yes! You do indeed...

Making it static will not affect the readability - only the accessibility as normal: you would not have access to any instance based data within the static thread.

If you have two tasks accessing the same data, then the data needs to be made thread safe - and in your case the almost certainly means locking.

The problem is that data access is not a "single instruction" process: even
C#
i++;
is three separate operations:
1) Fetch the current value of i
2) Add one to the value
3) Save the value to i
And multithreading means that the thread executing the instruction could be switched out part way through and a different thread get in and modify the value between the "fetch" and the "add" operations. So when the first thread gets back in to run, it overwrites the newer version the second thread just wrote. The situation is even worse when you have threads running on separate cores, as they can really mess each other up and case horrible, horrible intermittent errors (which never seem to happen in development, but happen every day in production...)

If you are accessing the same data in different threads, you need to consider locking it for safety.
 
Share this answer
 
Does this apply also if only thread A is writing data (variable) and all other threads are only reading data from thread A.

For example:
Thread A provides measure data (in endless loop it periodically measures data). Other threads are reading measure data and act when necessary or on user request.

On request thread A, can also take command from other threads (only one at the time) and set a value on device that thread A is communicating with.

For example:
thread B request: SET value x on device to 1

after that thread B waits until x is set to 1

while (measure.x != 1)
{
SET x = 1;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900