Created
April 25, 2020 02:13
-
-
Save elibroftw/dc61cbb99c41976c1b466ad4db6bd6d4 to your computer and use it in GitHub Desktop.
Examples of threading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
# there's also a multiprocessing module which I haven't used because its easier to communicate between threads | |
# than it is to communicate between processes | |
# for each section uncomment the code and run it | |
# 1. BASIC THREADING EXAMPLE | |
# def worker(): | |
# """thread worker function""" | |
# for j in range(2): | |
# print(j) | |
# time.sleep(1) | |
# | |
# | |
# threads = [] | |
# for i in range(5): | |
# t = threading.Thread(target=worker) | |
# threads.append(t) | |
# t.start() | |
# | |
# for t in threads: | |
# t.join() | |
# print('done') | |
# 2. ARGS THREADING EXAMPLE | |
# def worker(num): | |
# """thread worker function""" | |
# print(f'Worker: {num}') | |
# return num | |
# | |
# | |
# threads = [] | |
# for i in range(5): | |
# t = threading.Thread(target=worker, args=(i,)) | |
# threads.append(t) | |
# t.start() | |
# for t in threads: | |
# t.join() | |
# print('DONE') | |
# 3. KWARGS THREADING EXAMPLE | |
# def kwargs_thread(num=10): | |
# print(num) | |
# | |
# | |
# t = threading.Thread(target=kwargs_thread, kwargs={'num': 20}) | |
# t.start() | |
# 4. DAEMON THREADING EXAMPLE | |
# daemon threads exit when all non-daemon threads are done. default value is False | |
# def daemon(): | |
# print('SLEEPING FOR 2 SECONDS') | |
# time.sleep(2) | |
# print('DONE SLEEPING') | |
# | |
# | |
# d = threading.Thread(name='daemon', target=daemon, daemon=True) | |
# d.start() | |
# 5. NON-DAEMON THREADING EXAMPLE | |
# def non_daemon(): | |
# print('STARTING TO SLEEP') | |
# time.sleep(3) | |
# print('DONE SLEEPING') | |
# | |
# | |
# t = threading.Thread(name='non-daemon', target=non_daemon) | |
# t.start() | |
# print(t.is_alive()) | |
# t.join() | |
# print(t.is_alive()) | |
# there are also locks and other threading related objects but its not worth learning until you actually need to use | |
# them (advanced topic) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment