栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 多线程 threading.Thread 同时最多有 n 个线程

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 多线程 threading.Thread 同时最多有 n 个线程

Regular无限多线程
import threading
import numpy as np
import time

class BuildThread(threading.Thread):
	def __init__(self, name, alist):
		threading.Thread.__init__(self)
		self.alist = alist

	def run(self):
		self.alist.append(np.random.random_integers(1,10))
		time.sleep(1)

thread_num = 4 # 想要多少写多少

g_collect = []
threads = []


start_time = time.time()

for thread in range(thread_num):
	# 不使用多线程
	# g_collect.append(np.random.random_integers(1,10))
	# time.sleep(1)
	
	# 使用多线程
	_thread = BuildThread('Thread-1', g_collect)
	threads.append(_thread)
	_thread.start()

for thread in threads: # 保护:必须所有threads里的线程结束才可以进入下一步
	thread.join()

end_time = time.time()
run_time = end_time - start_time

print(g_collect)
print('run time: ', run_time)
同时最多有 4 个线程
import threading
import numpy as np
import time


class BuildThread(threading.Thread):
    def __init__(self, name, alist, threads):
        threading.Thread.__init__(self)
        self.alist = alist
        self.threads = threads

    def run(self):
        self.alist.append(np.random.random_integers(1,10))
        time.sleep(1)
        self.threads.remove(self)



thread_num = 10

g_collect = []
threads = []

start_time = time.time()
for thread in range(thread_num):
	
    while len(threads) >= 4: # 同时最多有4个线程
        pass
	
    _thread = BuildThread('Thread-{}'.format(threads), g_collect, threads)
    threads.append(_thread)
    _thread.start()


print(threads)

end_time = time.time()
run_time = end_time - start_time

print(g_collect)
print('run time: ', run_time)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/656562.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号