Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何保护Python多线程?_Python_Multithreading - Fatal编程技术网

如何保护Python多线程?

如何保护Python多线程?,python,multithreading,Python,Multithreading,我有一个类似于这样的python线程代码。但我不确定我的做法是否正确 Class MyThread(threading.thread): def __init__(self, thread_id, thread_name): self.thread_name = thread_name self.thread_id = thread_id def run(self): do_something() def do_someth

我有一个类似于这样的python线程代码。但我不确定我的做法是否正确

Class MyThread(threading.thread):
    def __init__(self, thread_id, thread_name):  
        self.thread_name = thread_name
        self.thread_id = thread_id

    def run(self):
        do_something()

def do_something():
    while True:
        do_something_else()
        time.sleep(5)


Class SomeClass:
    def __init__():
        pass
    def run():
        thread1 = MyThread(1, "thread1")
        thread2 = MyThread(2, "thread2")  
        thread3 = MyThread(3, "thread3")

def main():  
    agent = Someclass()  
    agent.run()
这是否是处理多线程的安全方法?它如何影响其他应用程序?有没有可能一个线程的执行会妨碍其他线程的执行?如果线程在任何循环中被阻塞,会发生什么情况


还有,如何确保线程不会因为任何原因永远被阻塞。如果它被阻塞,那么在固定的时间间隔之后,它应该优雅地出现并在下一个循环中继续。

这就是Python和其他一些语言引入
锁的原因


这将对您有所帮助,您需要阅读有关锁定、锁定和条件的内容

您的代码的线程安全性实际上取决于
do\u something()
do\u something\u else()
中的内容。如果只修改局部变量,那么它是线程安全的。但是,当您开始读取/修改共享变量/存储(如文件或全局变量)时,就需要使用锁或信号量之类的东西来确保线程安全

您可以阅读Python的
线程化
模块

这篇维基百科上的文章可能对你也有帮助


如果您需要编写多线程代码的示例,这里有一个使用不同同步机制的好方法。

您运行了吗?结果如何?预期的结果是什么?什么是做某事()和什么是做某事?是的,我运行了它。它起作用了。我避免使用函数代码。do_something()是每个线程调用的方法,它包含do_something_else()方法,每个线程需要定期执行该方法。但是我只是通过在do_something_else()中给出一个print语句进行测试。不,do_something_else()中的逻辑对于不同的线程是不同的。我想要的就是这样,每个线程都应该独立运行。此外,线程作业在我的代码中彼此不同。这实际上是我的问题,这是否是编写多线程程序的正确方法?好的,为什么使用while True:?这是消费者吗?还有一件事我要提醒你。。do_something()和do_something_else()实际上在同一个工作线程中线程需要定期执行某些操作这就是为什么,而True:condition.ok do_something()和do_something_else()在同一个线程中。。。我怀疑这是不是“别的”。。。。?