Tutorials to .com

Tutorials to .com » Dotnet » Foundation » A rather classic study of multi-threaded code

A rather classic study of multi-threaded code

Print View , by: iSee ,Total views: 14 ,Word Count: 464 ,Date: Tue, 25 Aug 2009 Time: 4:00 AM

A rather classic study of multi-threaded code.

1, uses a multi-thread synchronization problem.
2, uses a multi-threading problem with the order.

If you are interested please read the following code. Note that the order in which the code segment, think about the order of these codes can be interchangeable, and why? This should be helpful for learning. To illustrate, let all the threads Sleep for some time.

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, these two can swap? Why?
TestThread.m_testThreads [i]. Start ();
Thread.Sleep (100);

2, CallBack function, these two can swap? Why? What will be different results?
TestThread.m_Mutex.ReleaseMutex ();
Thread.Sleep (100);

3, the main function can be written like this? Why? What will be 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 is the role these few lines? So what kind of program, there is the problem? What kind of changes should be done?
TestThread.m_Mutex.WaitOne ();
int m_index = m_threadIndex;
TestThread.m_Mutex.ReleaseMutex ();

Just do study and discussions.

http://wucountry.cnblogs.com/archive/2006/06/19/429649.html


.NET foundation Articles


Can't Find What You're Looking For?


Rating: Not yet rated

Comments

No comments posted.