Bootstrap

Python多线程threading和多进程multiprocessing的区别及代码实现

1. 多线程threading

import time
from threading import Thread
 
 
def thread_read(data):
	while True:
		print('read data:', data)


def thread_write(data):
	i = 1
	while True:
		data[0] = i
		data[1] = i + 1
		print('write data:', data)
		i += 1

 
if __name__ == '__main__':
	data = [0, 0]
	t = Thread(target=thread_read, args=(data,))
	t.setDaemon(True)
	t.start()

	t2 = Thread(target=thread_write, args=(data,))
	t2.setDaemon(True)
	t2.start()

	while True:
		print('main')

资源监视器及部分命令行窗口运行结果如下图,只有一个Python进程

 

 

 

2. 多进程multiprocessing(共享数据失败)

from multiprocessing import Process
import time

def process_write(data):
	i = 1
	
;