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

Barbara Streisand
Release: 2024-10-25 08:09:28
Original
770 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!