Python 脚本在创建线程后不继续执行

问题描述 投票:0回答:1

我正在尝试编写一个套接字服务器程序,将键盘输入从我的 PC 发送到我的 Raspberry Pi,但是当我为一个函数创建一个新线程(其中有一个 while 循环)时,脚本执行不会继续,因为预期,但它被卡住了。这些是我的脚本:

import socket
import threading

class Server:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((host, port))
        self.server.listen()
        self.client = None
        self.message = ""

    def stream(self):
        while True:
            self.client.send(self.message.encode('utf-8'))

    def run(self):
        while True:
            print('Server is running and listening ...')
            self.client, address = self.server.accept()
            print(f'Connection is established with {str(address)}')
            thread = threading.Thread(target=self.stream)
            thread.start()
from server import Server
import threading

server = Server('192.168.178.30', 8001)
thread = threading.Thread(target=server.run)
thread.start()

while True:
    try:
        print("A")
    except KeyboardInterrupt:
        break

当我执行第二个程序时,它没有输出 A,而是只执行了第一个脚本的 run 函数的 while 循环中的内容。

python sockets python-multithreading
1个回答
1
投票

使用线程并不意味着Python可以在不同的内核上并行运行不同的代码。线程只是允许防止需要等待外部答案(通常通过网络)的函数阻止其他代码同时运行。由于您的服务器不断执行代码,甚至启动无数的新线程(永远运行),您的 CPU 根本无法执行第二个脚本的剩余部分。

请参阅线程文档

CPython 实现细节:在 CPython 中,由于 Global 解释器锁,一次只有一个线程可以执行Python代码 (尽管某些面向性能的库可能会克服 此限制)。如果您希望您的应用程序更好地利用 多核机器的计算资源,建议您 使用多处理或并发.futures.ProcessPoolExecutor。 但是,如果您想运行,线程仍然是一个合适的模型 同时执行多个 I/O 密集型任务。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.