Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading In Python

I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?

like image 289
Ian Avatar asked Jun 02 '09 14:06

Ian


People also ask

What is threading and multithreading in Python?

Multithreading (sometimes simply "threading") is when a program creates multiple threads with execution cycling among them, so one longer-running task doesn't block all the others. This works well for tasks that can be broken down into smaller subtasks, which can then each be given to a thread to be completed.

Is threading possible in Python?

Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library. The GIL does not prevent threading.


1 Answers

You have to consider multiple things if you want to use multiple threads:

  1. You can only run #processors threads simultaneously. (Obvious)
  2. In Python each thread is a 'kernel thread' which normally takes a non-trivial amount of resources (8 mb stack by default on linux)
  3. Python has a global interpreter lock, which means only one python instructions can be processed at once independently of the number of processors. This lock is however released if one of your threads waits on IO.

The conclusion I take from that:

  1. If you are doing IO (Turbogears, Twisted) or are using properly coded extension modules (numpy) use threads.
  2. If you want to execute python code concurrently use processes (easiest with multiprocess module)
like image 87
ebo Avatar answered Oct 20 '22 18:10

ebo