How Are Processes and Threads Different from Each Other in Python?

Problem scenario
You have heard of processes and threads in Python.  Are there illustrative Python programs that use processes and threads to demonstrate the differences between processes and threads themselves?

Solution
Here are two differences between processes and threads in Python:

Difference #1  Children processes keep running when parent process is killed.  Child threads stop process when parent process is killed.

Python script A (with spawned threads):

""" This program spawns no other PIDs.  In a duplicate terminal session, running the Linux command "sudo ps -ef | grep nameofprogrambelow.py" will show that no other PIDs are spawned when it executes."""
import _thread as thread, time
def counter(myId, count):
  for i in range(count):
    time.sleep(1) # Don't adjust this time.  The time on penultimate line is adjustable for experimentation and learning.
    print('[%s] => %s' % (myId, i))
for i in range(5):
  thread.start_new_thread(counter, (i, 5))
time.sleep(6)  # This duration affects the function b/c it too has time.sleep(1)
print('Main thread exiting.')   

Python script B (with process forks):

"""This program spawns other PIDs.  In a duplicate terminal session, running the Linux command "sudo ps -ef | grep nameofprogrambelow.py" will show other PIDs are spawned when it executes. 
The program below really does exit when you see "The main process has exited..."  Running this program will demonstrate the ability of child processes to survive their parent processes pre-termination:"""
import os, time 
def pidprinter(count):
  for i in range(count):
    time.sleep(1)
    print('[%s] => %s' % (os.getpid(), i))
    if (i == (count - 1)):
      print("Press enter to get to a command prompt.")
for i in range(7):
  pid = os.fork()
  if pid != 0:
    print('Process %d spawned' % pid)
  else:
    pidprinter(7)
    os._exit(0)
print('The main process has exited.  The following processes demonstrate existence without a parent process.')

Difference #2  If a Python program spawns a new process, Python waits for that process to return a value before interpreting the next line.

If a Python program starts a new thread, Python continues processing the next lines of code and does not wait for that thread to return a value before interpreting the next line.

Python script C (invokes threads only)

"""Running this Python program shows that the sleep(30) call (which  normally makes a program wait for 30 seconds) is not invoked because  threads do not cause the Python interpreter to wait for a return  value:"""
import _thread as thread, time  
def counter(myId, count):
  for i in range(count):
    time.sleep(30)
    print('[%s] => %s' % (myId, i))
    return myId
 x = thread.start_new_thread(counter, (0, 5))
print(x)
print("Got here")
print('Main thread exiting.') 

Python script D (invokes processes only)

 """Running this Python program shows that the sleep(30) call is invoked  because processes cause the Python interpreter to wait for a return  value:""" 
import os, _thread as thread, time 
def counter(myId, count):
  for i in range(count):
    time.sleep(30)
    x = os.getpid()
    return x
x = counter(0, 5)
print(x)
print("Got here")
print('Main thread exiting.') 

Leave a comment

Your email address will not be published. Required fields are marked *