Python:多进程共享变量

1. 进程

#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.线程

可以共享变量y,但是不能随意结束线程。

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

 

你可能感兴趣的:(Python)