python核心 多工 Linux

2021-08-18 02:37:45 字數 2692 閱讀 8081

1.程序的建立

os.fork() 建立乙個程序

import os

ret = os.fork() # 建立乙個新的程序

print("haha")

結果為haha

haha

import os

import time

ret = os.fork() # 建立乙個返回值等於0的子程序,而父程序是乙個大於0的值

if ret == 0:

while true:

print("---1---")

time.sleep(1)

else:

while true:

print("---2---")

time.sleep(1)

結果為:

---1---

---2---

---1---

---2---

---1---

---2---

---1---

---2---

....

os.getpid() # 獲取父程序建立的子程序的id

os.getppid() #獲取父程序的id

import os

ret = os.fork()

print(0)

if ret > 0:

print("---父程序---%d" %os.getpid())

else:

print("---子程序---%d--%d" %(os.getpid(), os.getppid()))

結果為20570

---父程序---20569

0---子程序---20570--20569

父程序中fork的返回值,就是剛剛建立出來的子程序的id

2.父子程序的先後順序

父程序執行完,父程序結束,不會等待子程序結束完才結束

import os

import time

ret = os.fork()

if ret == 0:

print("---子程序---")

time.sleep(5)

print(---子程序over---)

else:

print("---父程序---")

time.sleep(3)

print("over")

結果為---父程序---

over

---子程序---

---子程序over---

over

3.多個程序中,資料不共享

import os

import time

g_num = 100

ret = os.fork()

if ret == 0:

print("---process1---")

g_num +=1

print("---process1---%d" %g_num)

else:

time.slepp(3)

print("---process---")

print("---process2---%d" %g_num)

結果為---process1---

---process1---101

---process2---

---process2---100

4.多個fork

看入下**

import os

import time

ret = os.fork() # 建立了乙個程序,現在有兩個程序

if ret == 0:

print("---1---")

else:

print('---2---')

ret = os.fork() # 兩個程序分別建立了乙個程序,現在有四個程序

if ret == 0:

print('---11---')

else:

print('---22---')

結果為:

---2---

---22---

---11---

---1---

---22---

---11---

再看如下**

import os

import time

ret = os.fork() # 建立了乙個程序,現在有兩個程序

if ret == 0:

print("---1---")

else:

print('---2---')

ret = os.fork() # 乙個程序建立了乙個程序,現在有三個程序

if ret == 0:

print('---11---')

else:

print('---22---')

結果為:

---2---

---22---

---1---

---11---

python 多工回顧

回顧一下 python的多工 coding utf 8 import threading 執行緒 import gevent 協程 from time import sleep,ctime from multiprocessing import process 程序 from multiproces...

python多工 執行緒

併發 指的是任務數多餘cpu核數,通過作業系統的各種任務排程演算法,實現用多個任務 一起 執行 實際上總有一些任務不在執行,因為切換任務的速度相當快,看上去一起執行而已 並行 指的是任務數小於等於cpu核數,即任務真的是一起執行的 執行緒python的thread模組是比較底層的模組,python的...

python 多工介紹

多工介紹 在現實生活中,有很多的場景中的事情是同時進行的,比如跳舞和唱歌是同時進行的。在程式中,可以使用 來模擬唱歌和跳舞的功能 from time import sleep def sing for i in range 3 print 正在唱歌.d i sleep 1 def dance for...