<jupyter_start><jupyter_text>Table of Content- [12.1 Starting and Stopping Threads](12.1)- [12.4 Locking Critical Sections](12.4)- [12.8 Performing Simple Parallel Programing](12.8)- [12.9 Dealing with the GIL (and How to Stop Worring About it)](12.9) ---  12.1 Starting and Stopping Threads<jupyter_code>import time
from threading import Thread

def countdown(n):
    while n > 0:
        print('T-minux', n)
        n -= 1
        time.sleep(5)
        
t = Thread(target=countdown, args=(10,))
t.start()
if t.is_alive():
    print('Still Running')
else:
    print('Completed')
t.join()

if t.is_alive():
    print('Still Running')
else:
    print('Completed')<jupyter_output>T-minux 9
T-minux 8
T-minux 7
T-minux 6
T-minux 5
T-minux 4
T-minux 3
T-minux 2
T-minux 1
Completed<jupyter_text>DiscussionDue to Global Interpreter Lock(GIL), Python allows only one thread to exectute in the interpreter at any given time.Thus, Python threads are suited for- I/O handling- Concurrent execution that performs block opertations(e.g. waiting for I/O, waiting result from database)  and generally not be used for task that trying to achieve paralleism on multiple CPUs ---  12.4 Locking Critical Sections<jupyter_code>import threading

class SharedCounter:
    def __init__(self, initial_value=0):
        self._value = initial_value
        self._value_lock = threading.Lock()
        
    def incr(self, delta=1):
        with self._value_lock:
            self._value += delta
            
    def decr(self, delta=1):
        with self._value_lock:
            self._value -= delta<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10398505603985056, 'fraction_numerical': 0.029265255292652552, 'mean_word_length': 3.2967914438502675, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '595503', 'license': 'MIT', 'n_tokens_mistral': 556, 'n_tokens_neox': 521, 'n_words': 165, 'path': 'Ch12 - Concurrency.ipynb', 'repo_name': 'Lee-W/Python_Cookbook', 'size': '1606'}