Skip to content Skip to sidebar Skip to footer

Running Multiple Methods At Once In Python

I am trying to run a method which has an infinite loop in it to create a video display. This method is called within another loop that handles hardware input and as such cannot loo

Solution 1:

Yes, you can use Python's own threading module, or a cooperative microthreading module like gevent.

Note that Python's threading mechanism carries this disclaimer for CPython (the default Python implementation on most boxes):

Due to the Global Interpreter Lock, in CPython only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better of use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

Depending on how the underlying modules you are calling operate, you may find that while using threading, one thread won't give up control very often, if at all. In that case, using cooperative microthreading might be your only option.

Solution 2:

Yes, you can use Python's own multiprocessing module.

Note that Multiprocessing does not have to fight the GIL and can work simultaneously for everything you give it to do.

On the other hand there is a warning with the multiprocessing module, when you spawn a process it is a completely separate python interpreter. So its not just a OS controlled thread. It is in itself an entirely different process. This can add overhead to programs but the advantage of completely dodging the GIL makes this only a mild issue.

Post a Comment for "Running Multiple Methods At Once In Python"