繁体   English   中英

Python class 方法中的多线程

[英]Python Multithreading in a class method

当前代码:

my_dictionary = {}

class Test:
    def fun1(self, arg1):
        #...some code
        my_dictionary[arg1] = "some_value"
    
    def fun2(self):
        arg_list = ['a', 'b', 'c', 'd']
        threads = []
        for arg_val in arg_list:
            t = threading.Thread(target=self.fun1, args=(arg_val,))
            threads.append(t)

        for thread in threads: thread.start()
        for thread in threads: thread.join()
    

并在运行fun2时导致operation timed out错误

我是 Python 的新手,所以我真的不知道发生了什么

试试这个功能。

    def fun2(self):
            // ^---------------------------------------------- Add ----.
        arg_list = ['a', 'b', 'c', 'd'] //                 |           |
        threads = []                    //                 |           |
        for arg_val in arg_list:        //                 |           | 
            t = threading.Thread(target=self.fun1, args=[arg_val] daemon=True)
            threads.append(t)

        for thread in threads: thread.start()
        for thread in threads: thread.join()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM