Multi Thread

ParameterizedThreadStart | Monitor/Lock

A.Basically trying to do more than one thing at a time within a process

B.Passing parameter into thread (ParameterizedThreadStart)

1. Use class variable as parameter

Counter foo = new Counter(15);
ThreadStart job = new ThreadStart(foo.Count);
Thread thread1 = new Thread(job);
thread1.Start();

public Counter(int num)
{
this.number=num;

}

public void Count()
{
for (int i=0; i <number;i++)
{
Console.WriteLine ("Other thread: {0}", i);
}
}

2. ParameterizedThreadStart delegate only take 1 parameter with type of Object.
eg.

Counter sec =new Counter(5);
Thread thread2 = new Thread(new ParameterizedThreadStart(sec.DisplayURL));
thread2.Start("Geocities.com");

public void DisplayURL(object url)
{
Console.WriteLine("Passd in URL is :"+url.ToString()+" Port:"+number);

}

C. Exclusive Access
Thread can only has 1 monitor at the time. Before a thread acquires monitor,
the monitor owned by other thread must be released first.
Prevent > 1 threads access variable at the same time.

eg.
static readonly object countLock = new object();
for (int i=0; i < 5; i++)
{
Monitor.Enter(countLock);
int tmp = count;
Console.WriteLine ("Read count={0}", tmp);
Thread.Sleep(50);
tmp++;
Console.WriteLine ("Incremented tmp to {0}", tmp);
Thread.Sleep(20);
count = tmp;
Console.WriteLine ("Written count={0}", tmp);
Monitor.Exit(countLock);
Thread.Sleep(30);
}


for (int i=0; i < 5; i++)
{
lock (countLock)
{
int tmp = count;
Console.WriteLine ("Read count={0}", tmp);
Thread.Sleep(50);
tmp++;
Console.WriteLine ("Incremented tmp to {0}", tmp);
Thread.Sleep(20);
count = tmp;
Console.WriteLine ("Written count={0}", tmp);
}
Thread.Sleep(30);
}

@Copy right of Soon Lim 2006. All Right Reserved