Creating Threads in python

ghz 3months ago ⋅ 47 views

I have a script and I want one function to run at the same time as the other.

The example code I have looked at:

import threading

def MyThread (threading.thread):
    # doing something........

def MyThread2 (threading.thread):
    # doing something........

MyThread().start()
MyThread2().start()

I am having trouble getting this working. I would prefer to get this going using a threaded function rather than a class.

This is the working script:

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'

Answers

To run functions in parallel using Python's threading module, you don't need to define a class-based thread. You can create threads directly by passing the target functions to Thread, just as you're doing in your current script.

Here's a simpler example of how to get two functions to run in parallel using threads:

Step-by-Step Code:

  1. Import the necessary module (Thread from threading).
  2. Define the functions that will run in parallel.
  3. Create and start the threads, passing the functions as the target parameter.
  4. Optionally, use thread.join() to wait for threads to finish if needed.

Example Script:

from threading import Thread
from time import sleep

# Define two functions that will run in parallel
def help_function():
    print("Starting help function...")
    sleep(3)  # Simulate some work with sleep
    print("Help function done")

def nope_function():
    print("Starting nope function...")
    for i in range(5):
        print(f"Nope function, step {i+1}")
        sleep(1)
    print("Nope function done")

# Create threads targeting the functions
thread1 = Thread(target=help_function)
thread2 = Thread(target=nope_function)

# Start the threads
thread1.start()
thread2.start()

# Wait for both threads to complete
thread1.join()
thread2.join()

print("Both functions finished!")

Key Points:

  • target=help_function: This is how you assign a function to a thread. You don't call the function (i.e., no parentheses), you just pass the function name.
  • thread.start(): This starts the execution of the function in a new thread.
  • thread.join(): This ensures that the main program waits for the threads to finish before proceeding.

Output:

Starting help function...
Starting nope function...
Nope function, step 1
Nope function, step 2
Nope function, step 3
Help function done
Nope function, step 4
Nope function, step 5
Nope function done
Both functions finished!

This example runs help_function and nope_function in parallel. You can replace help_function and nope_function with your actual functions to achieve the same behavior.