Monday, April 3, 2023

Multithreading in Python

Multithreading makes threads appear to be running parallelly. We can do multithreading in Python using the threading module.


import threading

def even():

    for i in range(0,20,2):

        print(i)

def odd():

    for i in range(1,20,2):

        print(i)

if __name__ == "__main__":      # main method

    trd1 = threading.Thread(target=even)

    trd2 = threading.Thread(target=odd)

    trd1.start() 

    trd2.start() 

    trd1.join()   # waiting until thread 1 is done

    trd2.join()   # waiting until thread 2 is done

    print('End')


functions:

threading.active_count(), threading.main_thread(),  threading.current_thread().name 

threading.enumerate()    # list of active threads


Synchronization

A race condition occurs when two or more threads access shared data and try to change it at the same time. We use the locks to solve this problem. The locks provide two methods: acquire, release.

lock = threading.Lock() 

trd1 = threading.Thread(target=increment,args=(lock,))

def increment(lock):

    for _ in range(200000):

        lock.acquire()

        a += 1

        lock.release()

No comments: