Python Multithreading in a class method

Viewed 63

The current code:

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()
    

and causing operation timed out error while running fun2

I'm new to Python so i dont really know as to what's going on

1 Answers

Try it with this funciton.

    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()
Related