1import threading
2
3def worker(argument):
4 print(argument)
5 return
6
7for i in range(5):
8 t = threading.Thread(target=worker, args=[i])
9 t.start()
1from threading import Thread
2from time import sleep
3
4def threaded_function(arg):
5 for i in range(arg):
6 print("running")
7 sleep(1)
8
9
10if __name__ == "__main__":
11 thread = Thread(target = threaded_function, args = (10, ))
12 thread.start()
13 thread.join()
14 print("thread finished...exiting")
1# A minimal threading example with function calls
2import threading
3import time
4
5def loop1_10():
6 for i in range(1, 11):
7 time.sleep(1)
8 print(i)
9
10threading.Thread(target=loop1_10).start()
11
12# A minimal threading example with an object
13import threading
14import time
15
16
17class MyThread(threading.Thread):
18 def run(self): # Default called function with mythread.start()
19 print("{} started!".format(self.getName())) # "Thread-x started!"
20 time.sleep(1) # Pretend to work for a second
21 print("{} finished!".format(self.getName())) # "Thread-x finished!"
22
23def main():
24 for x in range(4): # Four times...
25 mythread = MyThread(name = "Thread-{}".format(x)) # ...Instantiate a thread and pass a unique ID to it
26 mythread.start() # ...Start the thread, run method will be invoked
27 time.sleep(.9) # ...Wait 0.9 seconds before starting another
28
29if __name__ == '__main__':
30 main()
1import threading
2import time
3
4def thread_function(name):
5 print(f"Thread {name}: starting")
6 time.sleep(2)
7 print(f"Thread {name}: finishing")
8
9my_thread = threading.Thread(target=thread_function, args=(1,))
10my_thread.start()
11time.sleep(1)
12my_second_thread = threading.Thread(target=thread_function, args=(2,))
13my_second_thread.start()
14my_second_thread.join() # Wait until thread finishes to exit
1def myFunction(x, y):
2 pass
3
4x = threading.Thread(target=myFunction, args=(x, y))
5x.start()
1x = threading.Thread(target=thread_function, args=(1,), daemon=True)
2x.start()
3# x.join()