为列表中的每个值创建和运行单线程

时间:2019-06-12 14:38:55

标签: python-3.x python-multithreading

所以我有一个物品清单

mylist = ["a", "b", "c", "d"]

我想在4个线程中执行一个函数,即mylist中每个项目一个线程。所以我做了以下

#!/usr/bin/python
import threading

def myfunc(item):
    print("item = " + str(item))
    print("Exiting threadID")

mylist = ["a", "b", "c", "d"]

threads = []
for index, item in enumerate(mylist):
    threads.append(threading.Thread(target=myfunc, args=(item)))

for th in threads:
    th.start()

for th in threads:
    th.join()

print( "Exiting Main Thread")
  1. 是否有更好的方法来做到这一点?也许使用泳池
  2. 在上面的示例中,我使用枚举将索引分配为线程ID。如何在上面的示例中分配我的自定义线程ID,以便可以在myfunc中打印线程ID?

0 个答案:

没有答案