Skip to main content
 首页 » 编程设计

Python无法启动多线程

2025年05月04日18thcjp

我有以下 python 代码 - 创建三个线程。但是创建第一个线程后控件似乎没有回来。输出是一个“.”,而不是三个预期的“.”。 worker函数有问题吗? 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 

请您参考如下方法:

我不确定这是否真的是一个答案(无论如何都不是你所期望的)但我不能做更多。我拿了你的代码并用

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

一切顺利,我可以看到来自 3 个线程的消息(1 秒间隔...),我还看到了 3 个点。恐怕问题出在 Msglyr 上。