0% found this document useful (0 votes)
4 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)
4 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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy