gpt4 book ai didi

python - 我可以让一种类方法在后台运行吗?

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:30 25 4
gpt4 key购买 nike

我想制作一个类似服务器的简单程序,它可以循环运行并读取和处理发送给它的消息。当我像 Server().start 一样启动它时,它显然会永远循环运行。有没有办法在后台运行它并向它提供数据,这将继续进行?

class Server:
def __init__(self):
self.messages = []
self.running = False

def start(self):
self.running = True
self.work()

def send_mess(self, message):
self.messages.append(message)

def handle_mess(self):
for mess in self.messages:
self.do_calculations(mess)

def work(self):
while self.running:
self.handle_mess(self)
self.do_some_important_stuff()

def do_some_important_stuff():
pass
def do_calculations():
pass

最佳答案

看起来你可以使用 Thread class from the threading module .

它的工作原理是继承它并重新定义run方法。然后您发出 obj.start() 并使 start 方法并行运行。

大致上,你的类可以这样定义(为了运行我对一些方法做了一些修正)

import threading

class Server(threading.Thread):
def __init__(self):
super(Server, self).__init__()
self.messages = []
self.running = False

def run(self): # changed name start for run
self.running = True
self.work()

def send_mess(self, message):
self.messages.append(message)

def handle_mess(self):
for mess in self.messages:
self.do_calculations(mess)

def work(self):
while self.running:
self.handle_mess()
self.do_some_important_stuff()

def do_some_important_stuff(self):
pass
def do_calculations(self):
pass


s = Server()
s.start() # now is in another another thread running
s.join() # wait for it to finnish

重要: 复制我发现非常有用的@Alfe 评论:

One MUST point out that by entering the world of concurrency (by threading) one opens a nasty can of worms. OP, you really really should read a little more about concurrency problems which occur in parallel environments. Otherwise you are bound to end with a serious problem sooner or later which you have no clue how to solve. See that you understand Queue.Queue (Queue.queue in Python3) and the things in threading like Events, Locks, Semaphores and what they are good for.

希望这对您有所帮助!

关于python - 我可以让一种类方法在后台运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21284319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com