0

Thread State and the Global Interpreter Lock:

The lock is also released around potentially blocking I/O operations like reading or writing a file, so that other Python threads can run in the meantime.

A related answer here by @Alex Martelli says:

All of Python's blocking I/O primitives release the GIL while waiting for the I/O block to resolve -- it's as simple as that! They will of course need to acquire the GIL again before going on to execute further Python code, but for the long-in-terms-of-machine-cycles intervals in which they're just waiting for some I/O syscall, they don't need the GIL, so they don't hold on to it!

*Does this mean when open or read or write happened to be blocking, the GIL is released so other threads run in parallel to the I/O operation?

Is it right to say then: there could possibly be multiple threads executing at the same time given one thread or more threads are blocked by an I/O operation and there would be only one single thread executing bytes codes. Whenever one of the blocked threads by the I/O operation needs to access Python objects it has to acquire the GIL first.

Community
  • 1
  • 1
direprobs
  • 3,601
  • 18
  • 38
  • your last paragraph is confusing, could you reword it? Unless you're using the multiprocessing library the interpreter is only executing one thing at a time. Once the interpreter has done its stuff it's in the OS's hands. – Gavin Achtemeier Jul 15 '17 at 21:51
  • Only one thread ever runs at a time, period. The GIL is used to insure this and it is release during I/O or when the current thread is otherwise blocked and can't run. See [**_Grok the GIL_**](https://opensource.com/article/17/4/grok-gil). – martineau Jul 15 '17 at 22:49
  • @minitotent I mean by that if you have thread A blocked by an I/O operation and your process consists of more than one thread say A, B and C. Because thread A is blocked by I/O, the GIL will be released to run B or C depending on the OS's scheduler. Hence, if the OS's scheduler decided to run say thread B there would be two threads concurrently running, thread A and B. – direprobs Jul 16 '17 at 08:29
  • @martineau I see the point now. Thanks for the resource that you provided, very informative. – direprobs Jul 16 '17 at 08:30

1 Answers1

1

Yes. When a thread is blocked waiting for IO to complete, the GIL is released, and thus available for some other thread to acquire.

gojomo
  • 40,306
  • 11
  • 74
  • 96