A relatively classic multi-threaded learning code.
1. Multi-thread synchronization problem is used.
2. The sequence problem of multi-threading is used.
If you are interested, please read the code below carefully. Pay attention to the order of the code segments and think about it. Can the order of these codes be interchanged? Why? This should be helpful for learning. For demonstration purposes, let all threads sleep for a while.
using System.Net;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace Webb.Study
{
class TestThread
{
static Mutex m_Mutex = new Mutex();
static Thread[] m_testThreads = new Thread[10];
static int m_threadIndex = 0;
static void ThreadCallBack()
{
TestThread.m_Mutex.WaitOne();
int m_index = m_threadIndex;
TestThread.m_Mutex.ReleaseMutex();
Console.WriteLine("Thread {0} start.",m_index);
for(int i=0;i<=10;i++)
{
TestThread.m_Mutex.WaitOne();
Console.WriteLine("Thread {0}: is running. {1}",m_index,i);
TestThread.m_Mutex.ReleaseMutex();
Thread.Sleep(100);
}
Console.WriteLine("Thread {0} end.",m_index);
}
public static void Main(String[] args)
{
Console.WriteLine("Main thread start.");
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_threadIndex = i;
TestThread.m_testThreads[i] = new Thread(new ThreadStart(ThreadCallBack));
TestThread.m_testThreads[i].Start();
Thread.Sleep(100);
}
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_testThreads[i].Join();
}
Console.WriteLine("Main thread exit.");
}
}
}
1. Can these two sentences in the main function be interchanged? Why?
TestThread.m_testThreads[i].Start();
Thread.Sleep(100);
2. Can these two sentences in the CallBack function be interchanged? Why? What would be a different outcome?
TestThread.m_Mutex.ReleaseMutex();
Thread.Sleep(100);
3. Can the main function be written like this? Why? What would be a different outcome?
public static void Main(String[] args)
{
Console.WriteLine("Main thread start.");
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_threadIndex = i;
TestThread.m_testThreads[i] = new Thread(new ThreadStart(ThreadCallBack));
TestThread.m_testThreads[i].Start();
TestThread.m_testThreads[i].Join();
Thread.Sleep(100);
}
Console.WriteLine("Main thread exit.");
}
4. What is the function of these sentences? So what kind of problems still exist in the program? What modifications should be made?
TestThread.m_Mutex.WaitOne();
int m_index = m_threadIndex;
TestThread.m_Mutex.ReleaseMutex();
only for learning and discussion.