0% found this document useful (0 votes)
6 views2 pages

Python Exp9

The document provides examples of basic threading and thread synchronization in Python. It demonstrates how to create and run threads using the threading module, as well as how to use locks to manage access to shared resources. The examples include starting threads, joining them, and printing results to show the behavior of concurrent execution.

Uploaded by

vraveena10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Python Exp9

The document provides examples of basic threading and thread synchronization in Python. It demonstrates how to create and run threads using the threading module, as well as how to use locks to manage access to shared resources. The examples include starting threads, joining them, and printing results to show the behavior of concurrent execution.

Uploaded by

vraveena10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

Basic Threading :-
import threading
import time
def thread_function(name):
print(f"Thread{name} started")
time.sleep(2)
print(f"Thread{name} ended")
thread1 = threading.Thread(target=thread_function, args=(1,))
thread2 = threading.Thread(target=thread_function, args=(2,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Main thread ended")

Output :
2. Synchronizing Threads with Lock :-
import threading
shared_resource = 0
lock = threading.Lock()
def thread_function():
global shared_resource
for _ in range(100000):
with lock:
shared_resource += 1
thread1 = threading.Thread(target=thread_function)
thread2 = threading.Thread(target=thread_function)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Shared resource value: ",shared_resource)

Output :

You might also like