0

I'm writing some code where one thread is using setters from a class and another thread is using getters from the same class.

My question is do I need to use lock or is there no problem when the threads call the getter and setter at the same time?

quamrana
  • 37,849
  • 12
  • 53
  • 71

1 Answers1

0

The most important use-case for locks is, to prevent threads B, C, and D from seeing some collection of shared data in an inconsistent or invalid state while thread A is in the middle of modifying the data.

The GIL won't prevent that from happening because the GIL does not prevent threads from being preemptively scheduled.

"setters" and "getters" are irrelevant. The point is, you have different threads accessing shared variables. If any of those variables has an important relationship to any other, and if a thread that updates them has to temporarily break that relationship, then you need locks. Without locks, the scheduler could "swap out" the thread that has temporarily broken the relationship, and some other thread could see the variables in the "broken" state.

A lock won't prevent the scheduler from "swapping out" any thread at any moment, but it will prevent other threads from seeing the mess before the first thread gets to run again, clean up the mess, and unlock the lock.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57