1. 程式人生 > >線程與進程的區別使用

線程與進程的區別使用

threads new t 改變 支持 只有一個 pre 形式 not affect

Threads share the address space of the process that created it; processes have their own address space.
1.線程共享創建它的進程的地址空間,進程,子進程有獨立的地址空間 Threads have direct access to the data segment of its process;
2.線程共享它的進程的數據
processes have their own copy of the data segment of the parent process.
3.子進程需要拷貝自己父進程的數據,等於也是獨立的數據 Threads can directly communicate with other threads of its process;
4.同一個進程的線程可以直接交互
processes must use interprocess communication to communicate with sibling processes.
進程彼此之間互相隔離,要實現進程間通信(IPC),multiprocessing模塊支持兩種形式:隊列和管道,這兩種方式都是使用消息傳遞的 New threads are easily created;
線程是輕量級的
new processes require duplication of the parent process.
子進程創建需要父進程的資源拷貝 Threads can exercise considerable control over threads of the same process;
線程可以實現多控制
多線程(即多個控制線程)的概念是,在一個進程中存在多個控制線程,多個控制線程共享該進程的地址空間
processes can only exercise control over child processes.
只能在子進程上添加控制 Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process;
修改子線程,可能會影響其他的線程
changes to the parent process does
not affect child processes.
子進程的改變不影響父進程 四 為何要用多線程

from threading import Thread
from multiprocessing import Process
import os
def work():
    global n
    n=2            #子進程的全局n=2
# if __name__==‘__main__‘:
#     n=100
#     p=Process(target=work)
#     p.start()
#     p.join()
#     print("zhu",n)
if __name__==__main__: n=100 t=Thread(target=work) t.start() t.join() print(zhu,n) #只有一個進程,線程共享進程的數據

線程與進程的區別使用