Creating Threads in Python without a Class
You're looking to run two functions simultaneously within your script. While you've come across some example code using a threaded function, you've encountered difficulties in making it work. This article will explore an alternative approach using threaded functions instead of a class.
The objective is to create two threads, each executing a distinct function concurrently. The example code you provided includes a class with two methods, help and nope. However, it's possible to achieve the same functionality using threaded functions.
Here's a revised version of your script:
<code class="python">from threading import Thread from time import sleep def threaded_function1(): # Performing task 1 def threaded_function2(): # Performing task 2 if __name__ == "__main__": thread1 = Thread(target = threaded_function1) thread2 = Thread(target = threaded_function2) thread1.start() thread2.start() thread1.join() thread2.join() print("Threads finished...exiting")</code>
In this script, we define two threaded functions, threaded_function1 and threaded_function2, which execute the desired tasks. We then create threads for each function using the Thread class. The target parameter specifies the function to be executed within the thread.
By calling start() on the threads, we initiate their execution. The join() method ensures that the main thread waits for the child threads to complete before proceeding. This guarantees that all tasks are finished before the program exits.
This method eliminates the need for a class and simplifies the thread creation process. You can seamlessly run multiple functions concurrently by following this approach.
The above is the detailed content of How to Create Threads in Python Without a Class?. For more information, please follow other related articles on the PHP Chinese website!