Home >Backend Development >Python Tutorial >How to execute two functions concurrently in a Python script using a threaded function?
Creating Threads in Python
Problem:
How can you execute two functions concurrently in a Python script using a threaded function instead of a class?
Working Script:
<code class="python">from threading import Thread class myClass(): def help(self): os.system('./ssh.py') def nope(self): a = [1,2,3,4,5,6,67,78] for i in a: print(i) sleep(1) if __name__ == "__main__": Yep = myClass() thread = Thread(target=Yep.help) thread2 = Thread(target=Yep.nope) thread.start() thread2.start() thread.join() print('Finished')</code>
Improved Solution:
<code class="python">from threading import Thread from time import sleep def threaded_function(arg): for i in range(arg): print("running") sleep(1) if __name__ == "__main__": thread = Thread(target=threaded_function, args=(10,)) thread.start() thread.join() print("thread finished...exiting")</code>
Explanation:
Instead of using a thread class, this improved script demonstrates how to create a thread directly by passing a target function and any necessary arguments to the Thread constructor. The target parameter specifies the function to be executed in a separate thread. In this case, the threaded_function() function is invoked concurrently with the main thread. The join() method ensures that the main thread waits for the thread to complete before continuing execution.
The above is the detailed content of How to execute two functions concurrently in a Python script using a threaded function?. For more information, please follow other related articles on the PHP Chinese website!