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, time
2
3def worker():
4 """thread worker function"""
5 print('Worker')
6 return
7
8threads = []
9for i in range(5):
10 t = threading.Thread(target=worker)
11 threads.append(t)
12 t.start()
13 print('Thread')
14
1#!/usr/bin/python
2
3import thread
4import time
5
6# Define a function for the thread
7def print_time( threadName, delay):
8 count = 0
9 while count < 5:
10 time.sleep(delay)
11 count += 1
12 print "%s: %s" % ( threadName, time.ctime(time.time()) )
13
14# Create two threads as follows
15try:
16 thread.start_new_thread( print_time, ("Thread-1", 2, ) )
17 thread.start_new_thread( print_time, ("Thread-2", 4, ) )
18except:
19 print "Error: unable to start thread"
20
21while 1:
22 pass