Reputation: 89
I am writing a code in python on a raspberry pi
while(true):
functionA
functionB
Function A is basically a command that captures images in png format. I do not want it be a blocking function. I want my code to proceed to function B, while in the mean time function A captures the image and makes the data ready for the next run.
I am confused on whether to use a thread or a process.
If I have to use a thread, when will it stop? Will it stop once after function A completes it's execution? And in that case, I need to call start method every time I have to start this thread? Or should I use a process and how will I go about it meaning when will a process stop.
Upvotes: 3
Views: 239
Reputation: 27125
CaitLAN's answer leaves out a couple of important details:
1) Communication between processes is much harder than communication between threads. Threads all live in the same address space, so communication between them is almost* as simple as thread A writes a variable, and thread B reads it.
Processes communicate with one another through shared pipes, shared files, network connections, or other means provided by the operating system. If you want to pass objects between processes, it's up to you (or up to some framework that you use) to provide means for "marshalling" and "unmarshalling" (a.k.a., "serializing", "pickling", ...) the objects.
*There's a devil lurking in that "almost", and it's more complicated than I want to describe here. Google "thread synchronization" and/or "memory visibility".
2) You can safely kill a process. You can never be sure about killing a thread. If there's any possibility that your functionA will go off the deep end, then it probably will take down your whole program if it's running in a thread within the program, but your program probably can recover* if functionA is running as a separate Python process.
*again, too much to write about in this space.
Upvotes: 2
Reputation: 3229
Let's be clear about the differences between a thread and a process. An informal definition: A thread is a sequence of code that executes as part of a process; A process may contain many threads which all share the same process space and virtual memory space. Threads will end (and terminate themselves) upon completion without necessarily ending the parent process. From what it sounds like, you should use a thread for executing functionA synchronously. A new process will definitely take more resources and sounds unnecessary. Also, yes you will need to create the thread again if you need that code to execute again after the thread has fully finished execution. On the other hand, you could write the code that executes within the new thread in a manner that loops indefinitely, if that approach seems appropriate for the task you are performing.
Upvotes: 2