Example Code
- Usage of lock to ensure threadsafe
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MultithreadedApp
{
class Program
{
//static long _value1;
private object
threadLock = new object();
void runcode()
{
lock (threadLock)
{
for (int
i = 0; i < 100; i++)
{
Console.WriteLine("Value of _value1 " + i);
}
}
}
static void Main(string[] args)
{
Thread[] agents = new
Thread[10];
Program[] P = new Program[10];
for (int i = 0; i
< 10; i++)
{
P[i] = new Program();
agents[i] = new Thread(P[i].runcode);
agents[i].Start();
}
Console.ReadLine();
}
}
}
Happy Learning!!!
No comments:
Post a Comment