多进程的全局变量不是共享的,所以,这里修改全局变量也不会被其他进程访问到,只能考虑用队列实现进程间通信,来结束其他进程。
多线程的全局变量共享,可以用这种方式来结束其他线程。
import threading
a = 0
lock = threading.Lock() # 实例化互斥锁对象, 方便之后的调用
def incr(n):
global a
for i in range(n):
lock.acquire() # 上锁的方法
a += 1
lock.release() # 解锁的方法
# 要注意的是上锁的位置是, 出现修改操作的代码
def decr(n):
global a
for i in range(n):
with lock: # 也可以直接使用with, 自动解锁
a -= 1
t_incr = threading.Thread(target=incr, args=(1000000,))
t_decr = threading.Thread(target=decr, args=(1000000,))
t_incr.start()
t_decr.start()
t_incr.join()
t_decr.join()
print(a)
# Result: 0
import threading
import time
class MyThread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
def run(self):
time.sleep(5)
print "This is " + self.getName()
if __name__ == "__main__":
t1=MyThread(999)
t1.setDaemon(True)
t1.start()
print "I am the father thread."
I am the father thread.
子线程t1中的内容并未打出。t1.setDaemon(True)将父线程设置为了守护线程。父线程打印内容后便结束了,不管子线程是否执行完毕。
from multiprocessing import Process
def fun1(name):
print('测试%s多进程' %name)
if __name__ == '__main__':
process_list = []
for i in range(5): #开启5个子进程执行fun1函数
p = Process(target=fun1,args=('Python',)) #实例化进程对象
p.start()
process_list.append(p)
for i in process_list:
i.join()
print('结束测试')
测试Python多进程
测试Python多进程
测试Python多进程
测试Python多进程
测试Python多进程
主线程结束
主进程在等待子进程先结束。
#coding:utf-8
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import os,time,random
def func(n):
print('%s is runing' %os.getpid())
time.sleep(0.2)
return n**2
if __name__ == '__main__':
executor=ProcessPoolExecutor(max_workers=6)
results=[]
for args in range(6):
future=executor.submit(func, args) # 异步提交任务
results.append(future.result())
executor.shutdown(True)
print(results)
import multiprocessing
import time
def hang():
while True:
print('hanging..')
time.sleep(10)
def main():
p = multiprocessing.Process(target=hang)
p.start()
time.sleep(2)
p.terminate()
p.join()
print('main process exiting..')
if __name__ == '__main__':
main()
import threading
import time
_FINISH = False
def hang():
while True:
if _FINISH:
break
print 'hanging..'
time.sleep(3)
def main():
global _FINISH
t = threading.Thread(target=hang)
t.start()
time.sleep(10)
_FINISH = True
t.join()
print 'main process exiting..'
if __name__ == '__main__':
main()
from multiprocessing.pool import ThreadPool
_FINISH = False
def hang(id):
global _FINISH
i = 0
while True:
if _FINISH:
break
print('id%d___%d'%(id, i))
i += 1
if i == 10:
_FINISH = True # 控制一个全局变量
def main():
global _FINISH
pool = ThreadPool(processes=3)
for i in range(16):
pool.apply_async(hang, args=(i, ))
while not _FINISH: # 循环等flag变中止信号True
pass
pool.terminate() # terminate 放在 join()之前,否报错
pool.join()
print('main process exiting..')
if __name__ == '__main__':
main()
# coding:utf-8
import time
from multiprocessing.pool import ThreadPool
_FINISH = False
_TIME_DELAY = 30 # n*0.1 s
def hang(id):
global _FINISH
n = 0
while True:
if _FINISH:
break
print('id%d___%d'%(id, n))
n += 1
if n == 10: ## 线程中的结束条件
_FINISH = True # 控制一个全局变量
def main():
global _FINISH
pool = ThreadPool(processes=3)
for i in range(16):
pool.apply_async(hang, args=(i, ))
j = 0
while not _FINISH and j < _TIME_DELAY: # 循环访问flag
j += 1
time.sleep(0.1)
if j == _TIME_DELAY:
_FINISH = True
pool.terminate() # terminate 放在 join()之前,否报错
pool.join()
print('main process exiting..')
if __name__ == '__main__':
t1 = time.time()
main()
print(time.time()-t1)
只看不评掉人品。