Python无法启动多个线程

时间:2014-06-20 05:07:44

标签: python multithreading

我有以下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 个答案:

答案 0 :(得分:1)

我不确定这是否真的是一个答案(不是你所期望的那样),但我不能做更多。我拿了你的代码并用

取代了工人
# Worker thread
def worker(num):
    i = 1
    while True :
        print("Thread", num, i);
        i += 1
        time.sleep(3)

一切顺利,我可以看到消息形成3个线程(1秒间隔...),我也看到3个点。我担心问题出在Msglyr

相关问题