Net Framework Multithreading Examples

This page demonstrates core multithreading concepts using a simplified example.

Example 1: Simple Thread

This demonstrates basic thread creation and basic operations.


                    import threading
                    def example_function(i):
                        print(f"Thread {i} started")
                        for j in range(5):
                            print(f"Thread {i} doing something")
                        print("Thread finished")
                    

Example 2: Thread with a Counter

This demonstrates thread-safe counter.


                    counter = 0
                    def increment():
                        global counter
                        counter += 1
                        return counter
                

Example 3: Thread with a Shared Resource

This demonstrates a thread-safe shared resource.


                    shared_resource = 0
                    def update(thread_id):
                        global shared_resource
                        shared_resource = thread_id
                        return shared_resource
                

Example 4: Using a Lock

Demonstrates a lock to protect shared resources.


                    import threading
                    lock = threading.Lock()
                    def worker():
                        with lock:
                            print("Worker received lock")
                            print("Worker done")
                        print("Worker finished")
                    

Example 5: Thread with a Timer

Demonstrates a simple timer to show progress.


                    import threading
                    def timer(duration):
                        for i in range(duration):
                            print(f"Timer: {i}")
                        print("Timer finished")