About threading, when to use the mutex for shared variable access

11OLSEN's icon

I was reading somewhere this rule for shared variables "if at least one thread writes to the variable you need a mutex".
I was always thinking only if more than 1 thread needs write access i need the exclusion. and the simplethread example from the SDK seem to confirm that. Can someone clarify?

Charly Beck's icon

it is not necessarry to protect data with an mutex if only one thread accesses it.

for max objects: they should be synchronized always because - depending on the object sending the message - this will be executed in a different thread. (time critial objects like metro or delay send in the timer thread.)

here's a good explanation about this:
https://cycling74.com/tutorials/advanced-max-learning-about-threading

note that there are also read-write locks around. because data needs not to be protected when various thread only read. i'm not sure if max provides rw-locks but it is a good thing for optimizing.

11OLSEN's icon

And by accessing you mean write access, right. Thanks for the video link, i've missed that one. I'm making a cup of tea now.

Charly Beck's icon

yes. a mutex does not make a difference between read and write. it just locks. but in general you only need protection when doing write access.

but notice a read could internally mean write. refering to the lazy load pattern.