Python實現進程以及應用

1、進程線程介紹

進程(Process)是計算機中的程序關於某數據集合上的一次運行活動,是系統進行資源分配和調度的基本單位,是操作系統結構的基礎。在早期面向進程設計的計算機結構中,進程是程序的基本執行實體;在當代面向線程設計的計算機結構中,進程是線程的容器。程序是指令、數據及其組織形式的描述,進程是程序的實體。

2、python進程創建

import os
import time
pid = os.fork()
if pid < 0:
    print('Create prcess failed')
elif pid == 0:
    # 子進程執行部分
    time.sleep(3)
    print('The new Process')
else:
    # 父進程執行部分
    time.sleep(4)
    print('The old Process')
print("Fork test over")

3、python線程創建增強版

import os, time
print("=========================")
a = 1
pid = os.fork()         # 創建進程
if pid < 0:
    print("Error")
elif pid == 0:
    print('Child process')      # 子進程
    print("a=", a)      # 父進程中a開闢年空間會被子進程獲取
    a = 13230           # 在子進程中修改變量只是修改了自己的空間變量
    print("a=", a)
else:
    time.sleep(1)
    print("Parent process")     # 父進程
    print("a=", a)

4、獲取進程PID號

import os,sys
pid = os.fork()     # 創建進程
if pid < 0:
    print("Error")
elif pid == 0:      # 子進程執行過程
    print("Child Process")
    print("Child PID:", os.getpid())    # 子進程PID
    os._exit(0)         # 進程退出
    print("Get parent PID:", os.getppid())  # 子進程獲取父進程的PID
else:
    print('Parent Process')
    print("Get Child PID:", pid)                # 子進程PID
    sys.exit("退出")      # 進程退出
    print("Get Parent PID:", os.getpid())       # 父進程PID

5、進程的應用—使用進程計算100000內的質數之和以及計算時間

import time
def timeit(f):
    def warpper(*args, **kwargs):
        start_time = time.time()
        res = f(*args, *kwargs)
        end_time = time.time()
        print("函數執行時間:%.6f" %(end_time-start_time))
        return res
    return warpper
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True
@timeit
def prime():
    sum_list = []
    for i in range(1, 100001):
        if is_prime(i):
            sum_list.append(i)
    print(sum(sum_list))
prime()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章