Home >Backend Development >Python Tutorial >How can I create threads in Python using functions without subclassing Thread?

How can I create threads in Python using functions without subclassing Thread?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 07:05:29746browse

How can I create threads in Python using functions without subclassing Thread?

Creating Threads in Python Using Functions

Problem:

To run two functions simultaneously in a Python script, you're unable to implement threading using the provided example code. You prefer to use a threaded function instead of a class-based approach.

Solution:

You can create threads using threaded functions in Python without using a subclass of Thread. Here's an example:

<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:

  • The threaded_function is defined with the argument arg and within it, you can perform any operations you wish.
  • In the main thread, an instance of the Thread class is created with threaded_function as its target and a tuple of arguments as the args parameter.
  • start() is called on the thread object to start its execution.
  • join() is used to wait for the thread to complete execution before continuing.

The above is the detailed content of How can I create threads in Python using functions without subclassing Thread?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn