Skip to content

Instantly share code, notes, and snippets.

@junaid109
Created May 16, 2023 09:21
Show Gist options
  • Save junaid109/c9f78165a981f50b33017f8941a9a7c7 to your computer and use it in GitHub Desktop.
Save junaid109/c9f78165a981f50b33017f8941a9a7c7 to your computer and use it in GitHub Desktop.
demonstrates a static string being accessed and updated by multiple threads using a lock for synchronization:
//demonstrates a static string being accessed and updated by multiple threads using a lock for synchronization:
using System;
using System.Threading;
public class Program
{
// Static string variable
private static string sharedString = "Initial Value";
// Lock object for synchronization
private static readonly object lockObject = new object();
public static void Main()
{
// Create multiple threads to update the shared string
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(UpdateSharedString);
thread.Start();
}
// Wait for all threads to finish
Thread.Sleep(2000);
// Print the final value of the shared string
Console.WriteLine("Final Value: " + sharedString);
}
public static void UpdateSharedString()
{
// Acquire the lock before accessing/updating the shared string
lock (lockObject)
{
// Print the current value of the shared string
Console.WriteLine("Current Value: " + sharedString);
// Update the shared string
sharedString += " Updated by Thread " + Thread.CurrentThread.ManagedThreadId;
}
}
}
//In this example, the sharedString variable is a static string that is accessed and updated by multiple threads. The lockObject is used as a synchronization mechanism to ensure that only one thread can access the shared string at a time. Each thread acquires the lock before accessing or updating the shared string, and releases the lock once it's done.
// By using the lock statement and the lockObject, we ensure that the shared string is accessed in a thread-safe manner, preventing any potential issues that may arise from concurrent access.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment