多个进程使用一个线程更好,还是每个进程使用一个线程更好?

2024-03-28 22:20:03 发布

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

如果我有一个Python类,它在主线程上运行一些进程,但是想同时运行其他进程,那么让每个不同的进程在自己的线程上运行更好吗,或者,如果可以的话,让所有进程都在一个指定的线程中运行更好吗?你知道吗

比如说。。。你知道吗

这样更好吗:

class blabla():

    def __init__():
        pass

    def some_process1(self):
        pass

    def some_process2(self):
        pass

    def some_process3(self):
        pass

    @threading
    def concurrent_process1(self):
        while True:
            pass

    @threading
    def concurrent_process2(self):
        while True:
            pass

    @threading 
    def concurrent_process3(self):
        while True:
            pass

还是这样更好:

class blabla():

    def __init__():
        pass

    def some_process1(self):
        pass

    def some_process2(self):
        pass

    def some_process3(self):
        pass

    @threading
    def thread(self):
        while True:
            self.concurrent_process1() 
            self.concurrent_process2()
            self.concurrent_process3()

    def concurrent_process1(self):
        pass

    def concurrent_process2(self):
        pass

    def concurrent_process3(self):
        pass

如果没有线程功能,这可能很难确定。我提供了我正在使用的:

def threaded(fn):
    """ Execute a function passed in a seperate thread
        and wrap for class decor style
    """
    def wrapper(*args, **kwargs):
        thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
        # This try block doesnt end the thread.. i don't know why, it should
        try:
            thread.start()
            #thread.daemon = True
        except (KeyboardInterrupt, SystemExit):
            thread.stop()
            sys.exit()
        return thread
    return wrapper

注意:我意识到我键入了@threading,函数名为thread()。。。呜呜。。。别理它。你知道吗

编辑:有人对我的线程功能有什么建议吗?你知道吗


Tags: selftrue进程defsomepass线程thread