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()