Python Threading Basics
Run code concurrently using threads.
Do multiple things at once.
Basic Thread
```python import threading import time
def task(name): print(f"{name} starting...") time.sleep(2) print(f"{name} done!")
Create threads t1 = threading.Thread(target=task, args=("Task 1",)) t2 = threading.Thread(target=task, args=("Task 2",))
Start threads t1.start() t2.start()
Wait for completion t1.join() t2.join()
print("All done!") ```
Thread with Function
```python import threading
def download_file(file_name): print(f"Downloading {file_name}...") # Download logic here print(f"Downloaded {file_name}")
files = ["file1.txt", "file2.txt", "file3.txt"] threads = []
for file in files: t = threading.Thread(target=download_file, args=(file,)) t.start() threads.append(t)
Wait for all for t in threads: t.join() ```
Thread Lock
```python import threading
counter = 0 lock = threading.Lock()
def increment(): global counter for _ in range(100000): with lock: counter += 1
threads = [threading.Thread(target=increment) for _ in range(10)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Counter: {counter}") # 1000000 ```
Remember
- Use threads for I/O-bound tasks - Not for CPU-intensive tasks (use multiprocessing) - Always join threads