I’m about to start a program using Python which is mostly doing polling, it will constantly read from the serial port (via PySerial) and read from a file descriptor which will be changing from time to time. I started looking into the threading module but then I kept finding more and more suggestions of using the multiprocessing module instead.
I’m not well versed in Python, coming from a mostly C background. What are the technical advantages of a threaded approach in Python?
In C, threads share data vs. having to set up some IPC to communicate, that seems to be the same for Python?
My usecase:
Main process (or thread?) -
start & initialize
|
V
spaw child----------------------> start & initialize
| |
V V
while (1) <------------+ wait for data<------+
| | | |
V | V |
read file descriptors | read from |
| | serial port<-----+ |
V | | | |
value changed? ------No--+ V | |
| ^ message done?--No-+ |
V | | |
Report change------------+ V |
over serial alert parent---------+
So I was thinking threads, since it will make sharing data got over serial easier, and they can have a shared handle to the serial port. Does this make sense, or am I thinking about this incorrectly from a Pythonic point of view?
multiprocessingis mainly used in Python to avoid the GIL (Global Interpreter Lock), which stops threads being useful for trying to compute in parallel – for resource access, threads are perfect, and the better option for ease of implementation.The GIL means that only one thread can operate on any Python object at the same time. This means that where you are trying to speed up computations, processes will be hamstrung by the other threads. In your use case, one thread will just be checking for new input, so this won’t cause any problems at all.