Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This is Thread-Safe right?

Just checking... _count is being accessed safely, right?

Both methods are accessed by multiple threads.

private int _count;  public void CheckForWork() {     if (_count >= MAXIMUM) return;     Interlocked.Increment(ref _count);     Task t = Task.Run(() => Work());     t.ContinueWith(CompletedWorkHandler); }  public void CompletedWorkHandler(Task completedTask) {     Interlocked.Decrement(ref _count);     // Handle errors, etc... } 
like image 376
Andres A. Avatar asked Oct 25 '13 14:10

Andres A.


People also ask

What is meant by thread-safe?

Thread safety is the avoidance of data races—situations in which data are set to either correct or incorrect values, depending upon the order in which multiple threads access and modify the data.

What is correctness in thread-safety?

Correctness means that a class conforms to its specification. You will agree that a good class specification will have all information about a class's state at any given time and it's post condition if some operation is performed on it.

What is meant by thread-safe in C?

A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. In C language, local variables are dynamically allocated on the stack.


1 Answers

This is thread safe, right?

Suppose MAXIMUM is one, count is zero, and five threads call CheckForWork.

All five threads could verify that count is less than MAXIMUM. The counter would then be bumped up to five and five jobs would start.

That seems contrary to the intention of the code.

Moreover: the field is not volatile. So what mechanism guarantees that any thread will read an up-to-date value on the no-memory-barrier path? Nothing guarantees that! You only make a memory barrier if the condition is false.

More generally: you are making a false economy here. By going with a low-lock solution you are saving the dozen nanoseconds that the uncontended lock would take. Just take the lock. You can afford the extra dozen nanoseconds.

And even more generally: do not write low-lock code unless you are an expert on processor architectures and know all optimizations that a CPU is permitted to perform on low-lock paths. You are not such an expert. I am not either. That's why I don't write low-lock code.

like image 82
Eric Lippert Avatar answered Oct 17 '22 00:10

Eric Lippert