multiple threads python code example

Example 1: create new thread 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")

Example 2: python running multiple threads at the same time

from threading import Thread
from time import sleep
# use Thread to run def in background
# Example:
def func1():
    while True:
        sleep(1)
        print("Working")

def func2():
    while True:
        sleep(2)
        print("Working2")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

Example 3: python threading

def myFunction(x, y):
  pass

x = threading.Thread(target=myFunction, args=(x, y))
x.start()

Example 4: how to execute program with multithreading python

#!/usr/bin/python

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass