DEV Community

Discussion on: How to make Python code concurrent with 3 lines

Collapse
 
yorodm profile image
Yoandy Rodriguez Martinez

Just add three things to your post:

  1. The API has been around since Python 3.2
  2. There's a backport for those still using 2.7.
  3. Concurrency is not parallelism
Collapse
 
rhymes profile image
rhymes • Edited

The API has been around since Python 3.2

This I said in the intro :D

There's a backport for those still using 2.7.

This I didn't know, I don't pay attention to what's going on in Python 2 anymore :D
Thanks for the info!

Concurrency is not parallelism

That is true, though in this context it's yes and no and depends on the number of cores.

Python has a GIL which simplifies its C API so that up to 1 thread is running at the same time when it's running bytecode.

Python though has a 1 by 1 threading model, where 1 Python thread is mapped onto 1 OS thread.

If the code is I/O bound, Python effectively releases the GIL, so the threads waiting for I/O are running free of it.

How many threads are running at the same time? One per core. I have 4 cores, so there are effectively 4 units of independent code running in parallel. The context switching (concurrency) does happen but there are up to 4 different parallel threads runnning.

I hope this clears it.

As the famous Go slides you linked state: concurrency is about dealing with lots of things at once (and you can be concurrent with only one thread and one process, see Node for example), parallelism is about doing multiple things at once.

In this case we have concurrent tasks that can be run in parallel if you have more than one core.

In Python there's only one moment when multiple threads achieve paralellism, and that's if they are waiting for I/O (and that's exactly why I chose this example :D) with multiple cores. If you want CPU bound parallelism in Python you have to use processes.

Collapse
 
jjangsangy profile image
Sang Han

How many threads are running at the same time? One per core. I have 4 cores, so there are effectively 4 units of independent code running in parallel.

Having 4 cores is irrelevant as the python threads can only utilize one logical core due to the GIL. The only possible way to release the GIL is using the C API, but it’s not advisable.

Thread Thread
 
rhymes profile image
rhymes • Edited

Python's I/O primitives are written with the C API.

They release the GIL when they are waiting for I/O, so in those moments when you're waiting for I/O, your program, for a little while is technically parallel.

A few moments of pure parallelism ;-)

So no, having multiple cores is not completely irrelevant.