带映射和池的多线程

时间:2019-05-27 17:35:58

标签: python python-3.x multithreading

我正在尝试遵循a multithread example,并使其适应我的代码。这是我读过的关于多线程的最简单的解释,当您有列表时很容易实现:

from multiprocessing.dummy import Pool as ThreadPool 
pool = ThreadPool(4) 
results = pool.map(my_function, my_array)

哪个是以下版本的多线程版本:

results = []
for item in my_array:
    results.append(my_function(item))

问题在于,对于我的示例,我有一个字典,我被困在代码的第一行,因为我必须创建一个函数,但是我不知道该怎么做,因为我需要在函数内部同时使用字典的键和值。

例如,对于此单线程版本:

thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

for key in thisdict: 
    print(key, thisdict[key])

如何使其适应地图和游泳池?

谢谢

1 个答案:

答案 0 :(得分:1)

如果要使用Pool.map(),请参见以下示例:

from multiprocessing.dummy import Pool as ThreadPool

def my_function(d):
    return d ** 2

my_array = [*range(20)]

pool = ThreadPool(4) 
results = pool.map(my_function, my_array)
print(results)

输出:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

已更新dict的版本:

def my_function(item):
    key, value = item
    return {"recieved_key": key, "recieved_value": value}

thisdict =  {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

pool = ThreadPool(3)
results = pool.map(my_function, thisdict.items())
print(results)