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 multiprocessing
2
3def worker(num):
4 """ Worker procedure
5 """
6 print('Worker:', str(num))
7
8# Mind the "if" instruction!
9if __name__ == '__main__':
10 jobs = [] # list of jobs
11 jobs_num = 5 # number of workers
12 for i in range(jobs_num):
13 # Declare a new process and pass arguments to it
14 p1 = multiprocessing.Process(target=worker, args=(i,))
15 jobs.append(p1)
16 # Declare a new process and pass arguments to it
17 p2 = multiprocessing.Process(target=worker, args=(i+10,))
18 jobs.append(p2)
19 p1.start() # starting workers
20 p2.start() # starting workers
1x = threading.Thread(target=thread_function, args=(1,), daemon=True)
2x.start()
3# x.join()
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