I have read something about threadsafety but I want to understand on what operations I need to put a lock.
For example lets say I want a threadsafe queue/
If the deqeue operation will return the first element if there is one, when do I need a lock? Lets say i’m using an abstract linked list for the entries.
Should write actions be locked? Or reading ones? Or both?
Hope if someone can explain this to me or give me some links.
Synchronization in concurrent scenarios is a very wide topic. Essentially whenever two or more threads have some shared state between them (counter, data structure) and at least one of them mutates this shared state concurrently with a read or another mutation from a different thread, the results may be inconsistent. In such cases you will need to use some form of synchronization (of which locks are a flavor).
Now going to your question, a typical code that does a dequeue is the following (pseudocode):
which may be executed concurrently by multiple threads. Although some queue implementations internally synchronize both the
queue is not emptyoperation as well as thequeue.dequeueoperation, that is not enough, since a thread executing the above code may be interrupted between the check and the actual dequeue, so some threads may find the queue empty when reaching the dequeue even though the check returned true. A lock over the entire sequence is needed:Note that the above may be implemented as a single thread-safe operation by some data structures, but I’m just trying to make a point here.