欢迎访问我的博客首页。
Python 进程和线程
1. 进程
不能使用成员函数创建进程,而且子进程与主进程共享变量需要借助 Manager。
#encoding=utf-8
from multiprocessing import Process, Manager
import os
import time
def process_fac(bill, ID, interval, **kwargs):
# 字典参数使用示例
bill.append(kwargs['BMW'])
bill.append(kwargs['Audi'])
# 整型参数使用示例
ID.value = os.getpid()
# 列表参数使用示例
x = 1
while(True):
bill.append(x)
x += 1
time.sleep(interval)
if __name__ == '__main__':
# 共享参数
manager = Manager()
bill = manager.list()
ID = manager.Value('i', 0)
p = Process(target = process_fac,
name = 'subprocess_1',
args = (bill, ID, 1),
kwargs = {'BMW': 298, 'Audi': 180})
p.start()
time.sleep(5)
p.terminate()
print bill
print ID.value
2. 线程
主线程及其子线程共享资源,所以使用线程很容易实现资源共享。Python 有 _thread 和 threading 两个线程包,其中后者功能更多。它们都可以使用成员函数和非成员函数创建线程。
2.1 使用非成员函数创建线程
下面的程序使用 _thread 包和非成员函数创建线程,换作 threading 也是可以的。使用 start_new_thread 函数创建线程即开始运行,没有 start 函数;即使不传参,第二个参数位置也要有个小括号。
import time
import _thread
def progress_fac(y):
a = 1
while True:
y.append(a)
a += 1
time.sleep(1)
if __name__ == '__main__':
y = []
_thread.start_new_thread(progress_fac, (y,))
time.sleep(10)
print(y)
2.2 使用成员函数创建线程
下面的程序使用 threading 包和成员函数创建线程,换作 _thread 也是可以的。使用成员函数创建线程,在线程函数中可以正常访问成员变量。
import time
import threading
class Example:
def __init__(self):
super(Example, self).__init__()
self.value = 17
self.stop_thread = False
def go(self):
# t = threading.Thread(target=Example.fac, args=(self,))
t = threading.Thread(target=self.fac)
t.start()
time.sleep(10)
self.stop_thread = True
def fac(self):
while not self.stop_thread:
print('v = ', self.value)
self.value += 1
time.sleep(1)
if __name__ == '__main__':
ex = Example()
ex.go()