python多线程阻塞调用后台运行

2024-10-04 09:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近在做一个程序(你可以从我之前问的问题中看到),我在理解和实现多线程方面遇到了真正的困难。在

我遵循了一个教程(binary tides)来设置UDP服务器,这很好用。但是,我遇到的问题是,当我在一个新线程上创建一个阻塞UDP套接字时,我最初创建线程的主程序中的代码不起作用。以下是我的一些代码:

在主.py公司名称:

from thread import*
import connections


start_new_thread(networkStart.startConnecton())
print 'This should print!'

在networkStart.py公司名称:

^{pr2}$

在连接.py公司名称:

def connectionListen():
    while 1:
            print 'waiting for connection'
            #wait to accept a connection - blocking call
            conn, addr = userData.s.accept()
            userData.clients += 1
            print 'Connected with ' + addr[0] + ':' + str(addr[1])
            #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments 
            start_new_thread(users.clientthread ,(conn, userData.clients))

我基本上只想在主.py在新线程上调用startConnection函数后(即,在这个实例中打印字符串)。在

我已经为这个程序苦苦挣扎了一段时间,Python对我来说是个新手,我发现它非常具有挑战性。我假设我在实现多线程的过程中一定犯了一些错误,任何帮助都将不胜感激!在


Tags: 代码pyimport程序名称new公司线程
1条回答
网友
1楼 · 发布于 2024-10-04 09:23:52

start_new_thread接收一个函数和一个参数列表,但您正在直接使用函数调用:start_new_thread(networkStart.startConnecton())。在

但是,我建议您使用threading模块(the official documentation does so),它具有更高的抽象级别。在

import threading
import connections

threading.Thread(target=networkStart.startConnecton).start()
print 'This should print!'

相关问题 更多 >