The difference between process and thread

Time:2020-10-15
  • Process is the basic unit of resource (CPU, memory, etc.) allocation. It is an instance of program execution.
  • Thread is the smallest unit of program execution. It is an execution flow of a process.
  • A process has its own independent address space. Every time a process is started, the system will allocate the address space for it and establish a data table to maintain the code segment, stack segment and data segment. This operation is very expensive
  • Threads share the data in the process and use the same address space. Therefore, the cost of switching a thread by the CPU is much less than that of the process. At the same time, the cost of creating a thread is much less than that of the process
  • Process implementation
from multiprocessing import Pool
import time
import random
import os


def work(msg):
    start = time.time()
    Print ("work {} starts execution with ID {}". Format (MSG, os.getpid ()))
    time.sleep(random.random()*2)
    stop = time.time()
    Print ("work {}." format (MSG, stop start))

p = Pool()
for i in range(10):
    #Non blocking operation
    p.apply_async(work, args=(i,))
    #Blocking is in progress
    # p.apply(work, args=(i,))


Print (start)
p.close()
p.join()
Print (end)
  • Thread implementation
 
import threading
import os
from time import sleep

def sorry(i):
    print('say sorry  {}'.format(i))
    sleep(1)

if __name__ == '__main__':
    for i in range(1,10):
        t = threading.Thread(target=sorry, args=(i,))
        t.start()

 

This paper was first published inPython black hole network, blog Garden updated synchronously