Home  >  Article  >  Backend Development  >  How to execute two functions concurrently in a Python script using a threaded function?

How to execute two functions concurrently in a Python script using a threaded function?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 08:09:28762browse

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!

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