Python无法启动多个线程
我有以下的Python代码,它创建了三个线程。但是在创建第一个线程后,控制权似乎没有返回。输出结果是一个点('.'),而不是预期的三个点。这个工作函数有什么问题吗?Msglyr
是一个内部消息传递库。
#!/usr/bin/python
import thread
import time
import Msglyr
# Worker thread
def worker(num):
testchannel = Msglyr.Channel("TEST-ASYNC-ROUTER-DEALER-CHANNEL", Msglyr.mlr.ASYNC_ROUTER_DEALER, Msglyr.mlr.ASYNC_DEALER_WORKER)
testchannel.setEndPoint(Msglyr.mlr.ASYNC_DEALER_WORKER, "inproc://test-pt")
testchannel.setEndPoint(Msglyr.mlr.ASYNC_DEALER_CLIENT, "tcp://127.0.0.1:5558")
while True :
msg = Msglyr.Message()
testchannel.receive(msg)
if msg.getnumParts() > 0:
msg.setPart(msg.getnumParts() - 1, "Worker : " + str(num))
testchannel.send(msg)
# Creating three threads
try:
thread.start_new_thread( worker, (1, ) )
print '.'
time.sleep(2)
thread.start_new_thread( worker, (2, ) )
print '.'
time.sleep(2)
thread.start_new_thread( worker, (3, ) )
print '.'
time.sleep(2)
except:
print "Error: unable to start thread"
print 'Started threads'
while 1:
pass
1 个回答
1
我不太确定这算不算一个真正的答案(反正不是你期待的那种),但我也做不了更多了。我把你的代码里的worker替换成了
# Worker thread
def worker(num):
i = 1
while True :
print("Thread", num, i);
i += 1
time.sleep(3)
一切都很顺利,我能看到来自3个线程的消息(每秒一次...),而且我也看到了那3个点。我担心问题出在Msglyr
上。