The difference between 2-3 multi-threaded and multi-process

A fast speed who opening?

1, open the main thread in the process

from threading import Thread

def work():
    print('hello')

if __name__ == '__main__':
    t=Thread(target=work)
    t.start()
    print('主线程/主进程')

Execution results are as follows, almost t.start () thread will be opened at the same time, and then print out a hello, thread creation overhead is minimal proof

hello
主线程/主进程

2, open the child process in the main process

from multiprocessing import Process

def work():
    print('hello')

if __name__ == '__main__':
    #在主进程下开启子进程
    p=Process(target=work)
    p.start()
    print('主线程/主进程')

Execution results are as follows, p.start () will open the signal sent to the process after the operating system, the operating system to the application memory space, make good copy of the parent process address space to the child, the cost is far greater than the thread

主线程/主进程
hello

Two look a look pid?

1, open multiple threads in the main process, the main process as pid related to each thread

from threading import Thread
import os

def work():
    print('hello',os.getpid())

if __name__ == '__main__':
    t1=Thread(target=work)
    t2=Thread(target=work)
    t1.start()
    t2.start()
    print('主线程/主进程pid',os.getpid())

Results of the

hello 7939
hello 7939
主线程/主进程 7939

2, open multiple processes, each process has a different pid

from multiprocessing import Process
import os

def work():
    print('hello',os.getpid())

if __name__ == '__main__':
    p1=Process(target=work)
    p2=Process(target=work)
    p1.start()
    p2.start()
    print('主线程/主进程',os.getpid())

Results of the

主线程/主进程 7951
hello 7952
hello 7953

Threads share data of the process within three the same process?

1, the address space between processes is isolated

from multiprocessing import Process
import os

def work():
    global n
    n=0

if __name__ == '__main__':
    n=100
    p=Process(target=work)
    p.start()
    p.join()
    print('主',n)

Execution results are as follows, there is no doubt that the child process has its own global p n-0 changed, but the change only its own view of the parent process is still 100 n

主 100

2, open multiple threads within the same process that share the process address space

from threading import Thread
import os

def work():
    global n
    n=0

if __name__ == '__main__':
    n=100
    t=Thread(target=work)
    t.start()
    t.join()
    print('主',n)

Execution results are as follows, view the result is zero, because the data is shared between threads in the same process within the process

主 0

Guess you like

Origin www.cnblogs.com/shibojie/p/11664774.html