为多个进程创建一个线程或为每个进程创建一个线程更好吗?

时间:2017-12-28 19:51:56

标签: python multithreading

如果我有一个在主线程上运行某些进程的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() ... woops ...只是忽略它。

编辑:有没有人对我的线程功能有任何建议?

0 个答案:

没有答案
相关问题