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()
1import threading, queue
2
3q = queue.Queue()
4
5def worker():
6 while True:
7 item = q.get()
8 print(f'Working on {item}')
9 print(f'Finished {item}')
10 q.task_done()
11
12# turn-on the worker thread
13threading.Thread(target=worker, daemon=True).start()
14
15# send thirty task requests to the worker
16for item in range(30):
17 q.put(item)
18print('All task requests sent\n', end='')
19
20# block until all tasks are done
21q.join()
22print('All work completed')
23
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
1import time
2from concurrent.futures import ThreadPoolExecutor, Future
3
4
5def test():
6 print("testing this")
7 time.sleep(2)
8 return "got"
9
10sample = ThreadPoolExecutor(max_workers=2, thread_name_prefix="sample")
11
12for _ in range(10):
13 got: Future = sample.submit(test)
14 print(got.result(timeout=3)) # waits for the result (like the join) # raise TimeoutError (doesn't quit thread tho)
15 # 2 threads at a time
16 # plus those 2 threads are reused instead of creating new thread every time
17 # that's how it's diff. from threading module
18
19sample.shutdown(cancel_futures=True) # refer: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown
1from multiprocessing import Pool
2
3def test( v ):
4 print(v)
5 return v
6
7if __name__ == '__main__':
8 with Pool(2) as p:
9 print(p.map(test, range(5)))