2

I am learning python language. I don't have a good understanding of threads and I can't think of a situation when you will need threading.Lock() as CPython's GIL only allows one thread to execute at a time so I think a critical section cannot be accessed by two threads at the same time.

wings
  • 338
  • 4
  • 15
  • 3
    It's generally not true. Imagine a situation in which a critical section consist of non-atomic operation (i.e. several operations). Of course GIL does not allow to run same bytecode by 2 threads at once, but context may be switched between two threads accessing the same critical section. – running.t Apr 16 '18 at 14:16
  • thanks! got it now :) – wings Apr 16 '18 at 14:18
  • I didn't find it before --> https://stackoverflow.com/questions/105095/are-locks-unnecessary-in-multi-threaded-python-code-because-of-the-gil? – wings Apr 16 '18 at 14:42

1 Answers1

3

The GIL guarantees that one single process is executed at any time. However, when using threads you may have files or other objects shared between threads. Even if only one thread is active at any moment (because of the GIL), multiple threads may have access to the same object, here is when locks enter into play. Using threading.Lock() avoids that a given object is accessed by a second thread while a first thread is already using it.

Let's say you have a file and two threads want to write the same file. The GIL gurantee that only one WRITE operation it is executed at a given moment, the Lock will guarantee that only a single thread can write that file.

alec_djinn
  • 10,104
  • 8
  • 46
  • 71