我只是在尝试如何使用 multiprocessing.Lock()
从以下示例工作:
http://docs.python.org/2/library/multiprocessing.html
这个例子其实:
from multiprocessing import Process, Lock
def f(l, i):
l.acquire()
print 'hello world', i
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f, args=(lock, num)).start()
我有这个作为我的代码:
from multiprocessing import Process, Lock
import datetime
import time
import random
def function(lock, i):
now = datetime.datetime.now()
time.sleep(random.randint(0,3))
lock.acquire()
print "%s says hello, World! at time: %s" % (i,now)
lock.release()
lock = Lock()
for i in range(2):
Process(target=function,args=(lock,i)).start()
在 shell 中运行它会导致计算机锁定在 100% cpu,并在 cmd 中运行数十个 python.exe。一直在打印来自进程 0 或 1 的消息。看着这个例子,我意识到我错过了:
if __name__ == '__main__':
所以我加了它害怕货物代码神,孤注一掷:
from multiprocessing import Process, Lock
import datetime
import time
import random
def function(lock, i):
now = datetime.datetime.now()
time.sleep(random.randint(0,3))
lock.acquire()
print "%s says hello, World! at time: %s" % (i,now)
lock.release()
if __name__ == "__main__":
lock = Lock()
for i in range(2):
Process(target=function,args=(lock,i)).start()
印刷:
1 says hello, World! at time: 2013-05-20 19:40:13.843000
0 says hello, World! at time: 2013-05-20 19:40:13.843000
编辑认为这可能与命名空间有关,所以我尝试了:
from multiprocessing import Process, Lock
import datetime
import time
import random
def function(l, i):
now = datetime.datetime.now()
time.sleep(random.randint(0,3))
l.acquire()
print "%s says hello, World! at time: %s" % (i,now), i
l.release()
lock = Lock()
for i in range(2):
Process(target=function,args=(lock,i)).start()
还是同样的问题
让我感到困惑?!任何人都可以对此做出解释吗?
最终编辑:
这就是我现在完成我的小示例代码的方式:
from multiprocessing import Process, Lock
import datetime
import time
import random
print "imports done"
def function(l, i):
now = datetime.datetime.now()
time.sleep(random.randint(0,3))
l.acquire()
print "%s says hello, World! at time: %s" % (i,now)
l.release()
def main():
lock = Lock()
for i in range(2):
Process(target=function,args=(lock,i)).start()
if __name__ == "__main__":
main()
哪个打印:
imports done
imports done
imports done
1 says hello, World! at time: 2013-05-20 23:26:41.015000
0 says hello, World! at time: 2013-05-20 23:26:41.015000