Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x “concurrent.futures.map”是线程安全的吗?_Python 3.x_Concurrent.futures - Fatal编程技术网

Python 3.x “concurrent.futures.map”是线程安全的吗?

Python 3.x “concurrent.futures.map”是线程安全的吗?,python-3.x,concurrent.futures,Python 3.x,Concurrent.futures,我发现文档中没有提到它:参考文献: 据 当与未来关联的可调用对象等待时,可能会发生死锁 关于另一个未来的结果 这里的两个例子说明了死锁是如何发生的。尝试用.map()替换.submit(),并进行其他必要的更改 发动机罩下: 根据Python的python3.6/concurrent/futures/thread.py模块(在系统中搜索此文件),类ThreadPoolExecutor实际上使用queue.queue()(参见第107行)来实现Python线程,并使用原语threading.Loc

我发现文档中没有提到它:

参考文献:

当与未来关联的可调用对象等待时,可能会发生死锁 关于另一个未来的结果

这里的两个例子说明了死锁是如何发生的。尝试用
.map()
替换
.submit()
,并进行其他必要的更改

发动机罩下:

根据Python的
python3.6/concurrent/futures/thread.py
模块(在系统中搜索此文件),类
ThreadPoolExecutor
实际上使用
queue.queue()
(参见第107行)来实现Python线程,并使用原语
threading.Lock()
(参见第110行)来锁定线程

说明:

如果对您来说,“线程安全”是指程序中的多个线程,每个线程都试图访问内存中的公共数据结构或位置,那么您应该知道,
concurrent.futures.ThreadPoolExecutor
一次只允许一个线程访问内存中的公共数据结构或位置;
threading.Lock()
原语用于管理此操作。当一个线程中的函数需要等待另一个线程中的结果时,可能会发生死锁,代码将无法工作;您应该避免这种情况

from concurrent.futures import ThreadPoolExecutor, as_completed
import time

resultDict = {0: [], 1: [], 2: [], 3: [], 4: []}
resultDict1 = {0: [], 1: [], 2: [], 3: [], 4: []}

def appendResult(a, b):
  result = a ** b
  resultDict[result % 5].append(result)
  time.sleep(1)

def appendResult1(a, b):
  result = a ** b
  resultDict1[result % 5].append(result)
  time.sleep(1)

startTime = time.time()
processes = []
with ThreadPoolExecutor(max_workers=12) as executor:
  for i in range(100):
    processes.append(executor.submit(appendResult, i, 2))

for task in as_completed(processes):
  task.result()

print("Cost", time.time() - startTime, "s")


startTime = time.time()
for i in range(100):
  appendResult1(i, 2)
print("Cost", time.time() - startTime, "s")
是的,它是线程安全的。所以在上面代码的末尾,resultdct和resultdct1是相同的