Asp.net| Comparison | multithreading
A more classic multithreaded learning code.
1, the use of multithreading synchronization problem.
2, the use of the sequence of multithreading problems.
If you are interested please read the following code carefully. Note The order of the Code snippets, and think about whether the order of the code can be exchanged, and why? This should be very helpful to study. To demonstrate, let all the 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, the main function of the two sentences can be interchangeable? Why?
Testthread.m_testthreads[i]. Start ();
Thread.Sleep (100);
2, callback function can be exchanged in these two sentences? Why? What are the different results?
TestThread.m_Mutex.ReleaseMutex ();
Thread.Sleep (100);
3, can the main function be written like this? Why? What are the different results?
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 are the functions of these sentences? So what kind of problems are there in the program? What kind of modifications should be made?
TestThread.m_Mutex.WaitOne ();
int m_index = M_threadindex;
TestThread.m_Mutex.ReleaseMutex ();
Only do study discussion.