美文网首页
python多进程与多线程linux与windows设计实现

python多进程与多线程linux与windows设计实现

作者: 文靖_e4ef | 来源:发表于2018-09-14 22:02 被阅读0次

python3.6.5
linux创建子进程:
'''
import os
print('Process(%s)start...'%os.getpid())
pid = os.fork()
if pid == 0:
print('this is a child process(%s)\n this is a parent process(%s).'%(os.getpid(),os.getppid()))
else:
print('this (%s)have created a child process(%s).'%(os.getpid(),pid))
'''
运行结果:
Process(4758)start...
this (4758)have created a child process(4759).
this is a child process(4759)
this is a parent process(4758).

windows创建子进程:
'''
from multiprocessing import Process
import os
def proc(name):
print('this is a child process %s(%s)...'%(name,os.getpid()))

if name == 'main':
print('this is a parent process %s.'%os.getpid())
p = Process(target = proc, args = ('test',))
print('process will start')
p.start()
p.join()
print('process end.')
'''
运行结果:
this is a parent process 31240.
process will start
this is a child process test(29392)...
process end.

多线程设计(windows与linux代码相同):
'''
import time,threading
def loop():
print('%s start...'%threading.current_thread().name)
for n in range(5):
print('%s...%s'%(threading.current_thread().name,n))
time.sleep(1)
print('%s ended.'%threading.current_thread().name)
print('%s start...'%threading.current_thread().name)
t = threading.Thread(target = loop,name = 'Sub_Thread')
t.start()
t.join()
print('%s ended.'%threading.current_thread().name)
'''
运行结果:
Sub_Thread start...
Sub_Thread...0
Sub_Thread ended.
Sub_Thread start...
Sub_Thread...1
Sub_Thread ended.
Sub_Thread start...
Sub_Thread...2
Sub_Thread ended.
Sub_Thread start...
Sub_Thread...3
Sub_Thread ended.
Sub_Thread start...
Sub_Thread...4
Sub_Thread ended.
Sub_Thread start...
MainThread ended.

多线程中需用threading.lock()方法进行锁定,以防止进程运行过程中,被线程修改。

如下例所示:

'''

import time,threading
a = 0
lock = threading.Lock()
def change_it(n):
global a
a = a + n
a = a - n
def run_thread(n):
for i in range(1000000):
lock.acquire()
try:
change_it(n)
finally:
lock.release()
TR1 = threading.Thread(target = run_thread,args = (5,))
TR2 = threading.Thread(target = run_thread,args = (8,))
TR1.start()
TR2.start()
TR1.join()
TR2.join()
print(a)
'''
运行结果为:0,如不锁定,结果可能为16,13等多个结果。

相关文章

网友评论

      本文标题:python多进程与多线程linux与windows设计实现

      本文链接:https://www.haomeiwen.com/subject/yaeagftx.html