Python中的多线程 - 背景中运行的阻塞调用

4 投票
1 回答
589 浏览
提问于 2025-04-17 19:06

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

我跟着一个教程(binary tides)设置了一个UDP服务器,运行得很好。不过,我遇到的问题是,当我在一个新线程中创建一个阻塞的UDP套接字时,我在主程序中创建线程的代码就不工作了。这是我部分代码:

main.py:

from thread import*
import connections


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

networkStart.py:

def startConnecton():
    userData.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
    print 'Socket created'
    try:
        userData.s.bind((HOST, PORT))
    except socket.error, msg:
        print 'Bind failed. Error code: ' +str(msg[0]) + 'Message' +msg[1]
        sys.exit()
    print 'Socket bind complete'
    userData.s.listen(10) 
    # Set the socket to listening mode, if there are more than 10 connections waiting reject the rest
    print 'Socket now listening' 
    #Function for handling connections. Each new connection is handled on a separate thread
    start_new_thread(connections.connectionListen())

connections.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))

我基本上只是想在调用startConnection函数后,能够在main.py中执行任何代码(比如在这个例子中打印一个字符串)。

我在这个程序上挣扎了很久,Python对我来说是个新东西,我觉得这很有挑战性。我想我在实现多线程的方式上可能犯了一些错误,任何帮助都将非常感激!

1 个回答

5

start_new_thread 这个函数需要你传入一个函数和一组参数,但你直接在里面调用了这个函数:start_new_thread(networkStart.startConnecton())

不过,我建议你使用 threading 模块(官方文档也是这么说的),因为它的抽象层次更高,更容易使用。

import threading
import connections

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

撰写回答