Python-多线程注意事项
锁申请位置错误导致内存泄露-多线程内存泄露注意事项
# encoding: UTF-8
import threading
import time
def show_fun(sem, n):
# 不能放在这里
# sem_lock.acquire()
print("{0} start -- {1}".format(time.ctime(), n))
print "working"
time.sleep(2)
print("{0} end -- {1}".format(time.ctime(), n))
sem.release()
if __name__ == '__main__':
max_connections = 5
semaphore = threading.BoundedSemaphore(max_connections)
thread_list = list()
for i in range(8):
# 锁申请必须在外部申请,而不是在show_fun内部,因为t.start()会实例化所有对象
# 锁在show_fun内部对象内,会导致所有对象被实例化,实例化后再被acquire,并发越大,资源暂用率明显
semaphore.acquire()
t = threading.Thread(target=show_fun, args=(semaphore, i,))
thread_list.append(t)
t.start()
# 等待所有子进程结束
for t in thread_list:
t.join()
- 原文作者:zaza
- 原文链接:https://zazayaya.github.io/2021/03/23/python-threading-memory-leak.html
- 说明:转载本站文章请标明出处,部分资源来源于网络,如有侵权请及时与我联系!