Python:在第一个函数保持运行的同时运行第二个函数

2024-10-02 18:26:42 发布

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

我想运行两个函数而不等待第一个函数完成。我需要运行一个函数“ListeningToReceive”使端口监听接收来自远程代理的数据,当监听该端口时,它执行第二个函数“RunRemoteAgents”来运行远程代理,以使它们向侦听端口发送数据。 我使用线程,但它似乎不起作用,它只是让端口监听,而不执行第二个函数

#!/usr/bin/python
import threading

def ListeningToReceive():
        print "The port is open to receive data"
def RunRemoteAgensts():
        print "Running remote agents to send Data to the open port here"
if __name__ == "__main__":
        thread1 = threading.Thread(target=ListeningToReceive)
        thread2 = threading.Thread(target=RunRemoteAgents)
        thread1.start()
        thread2.start()

Tags: to端口函数代理target远程portdef
1条回答
网友
1楼 · 发布于 2024-10-02 18:26:42

CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

请改用多处理:

from multiprocessing import Process
import time

def f(name):
    print 'hello', name
    time.sleep(10)
    print "f is done"

def f2():
    print "this is funct2"
if __name__ == '__main__':
    p1 = Process(target=f, args=('bob',))
    p2 = Process(target=f2, args=())

    processes = list()
    processes.append(p1)
    processes.append(p2)

    for p in processes:
        p.start()

相关问题 更多 >