Bru*_*cci 2 python multithreading
我试图解决的问题是映射多线程庄园中的函数列表.这些函数既可以打印出来,也可以返回值.这些返回值中的每一个都将存储在列表中.这是代码......
import threading
import time
def PauseAndPrint1Seconds(num):
time.sleep(1)
print("Finished Pausing" + num)
return [1]
def PauseAndPrint2Seconds(num):
time.sleep(2)
print("Finished Pausing" + num)
return [2, 2]
def PauseAndPrint3Seconds(num):
time.sleep(3)
print("Finished Pausing" + num)
return [3, 3, 3]
def PauseAndPrint4Seconds(num):
time.sleep(4)
print("Finished Pausing" + num)
return [4, 4, 4, 4]
myfuncs = [PauseAndPrint1Seconds, PauseAndPrint2Seconds, PauseAndPrint3Seconds, PauseAndPrint4Seconds]
result = [None] * len(myfuncs)
def wrapFunc(i, num):
result[i] = myfuncs[i](num)
mythreads = [threading.Thread(target=wrapFunc, args = (i, " 12345")) for i in range(len(myfuncs))]
map(lambda x: x.start(), mythreads)
map(lambda x: x.join(), mythreads)
Run Code Online (Sandbox Code Playgroud)
线程从未启动过,我得到了回复......
>>> map(lambda x: x.start(), mythreads)
<map object at 0x7fd1a551b3c8>
>>> result
[None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
如果我将map函数更改为简单循环,它似乎可以工作
>>> for x in mythreads:
... x.start()
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
>>> result
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
Run Code Online (Sandbox Code Playgroud)
还奇怪的是,如果我用list()调用包装地图,确实无法正常工作的地图函数.
>>> list(map(lambda x: x.start(), mythreads))
[None, None, None, None]
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
>>> result
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
Run Code Online (Sandbox Code Playgroud)
包装事物的几个... 1.我是Python的新手很抱歉,如果我错过了一些基本的东西2.我知道有一个更简单的方法来做到这一点.这是我理解的问题.
这是Python2和Python3之间的区别.
Python3返回一个地图对象,它记住了需要做什么(比如生成器),但是在你要求结果之前不做任何工作(从地图对象的结果创建一个列表就是一次性要求它们)
map在Python2中已经返回一个列表,因此类似于list(map(...))Python3
通常不会将Pythonic视为使用地图或列表理解仅仅是因为它们的副作用.如果您只使用了一个for循环,那么事情发生的时间就没有歧义
for x in mythreads:
x.start()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
333 次 |
| 最近记录: |