Not enough information to give a really good answer. How is s "published" to other threads? How do other topics subscribe to s ? In what data structure are struct s objects stored?
So, I will give a general answer:
For each type of data that is shared between streams, synchronization is required. This includes generic pointers.
About pointers:
You may have heard that on some regular CPUs, the load / stock of correctly aligned pointers is atomic (this does not apply to all CPUs or for all types of pointers, for example: distant pointers to an x86 non-atom). Stay away from using this if you do not have a complete understanding of your CPU / VM memory model, there are many subtle things that can go wrong if you do not take locks (locks provide fairly strong guarantees).
Edit:
In your example, neither th1 nor th2 changes the list, they only change the elements of the list. So, in this particular case, you do not need to block the list, you just need to block the list items (the pointer conceptually belongs to the implementation of the linked list).
In more typical cases, some threads will move around the list, while others will change the list (add and remove items). This requires locking the list or using some kind of algorithm without locking.
There are several ways to make this lock.
- Have a global lock on the list and use it also for list items.
- Use hierarchical locking , lock the list, and lock each item. To read / change an element, you first need to lock in the list, find the element, take the element lock, release the list lock, process the element, and finally release the element lock. This is useful if you need to perform complex element processing and do not want to prevent other threads from accessing the list. You must ensure that you always take locks in the same order to avoid deadlocks.
source share