| using namespace System; using namespace System::Threading; int main() { /*1*/ MessageBuffer^ m = gcnew MessageBuffer; /*2a*/ ProcessMessages^ pm = gcnew ProcessMessages(m); /*2b*/ Thread^ pmt = gcnew Thread(gcnew ThreadStart(pm,&ProcessMessages::ProcessMessagesEntryPoint)); /*2c*/ pmt->Start(); /*3a*/ CreateMessages^ cm = gcnew CreateMessages(m); /*3b*/ Thread^ cmt = gcnew Thread(gcnew ThreadStart(cm, &CreateMessages::CreateMessagesEntryPoint)); /*3c*/ cmt->Start(); /*4*/ cmt->Join(); /*5*/ pmt->Interrupt(); /*6*/ pmt->Join(); Console::WriteLine("Primary thread terminating"); } public ref class MessageBuffer { String^ messageText; public: void SetMessage(String^ s) { /*7*/ Monitor::Enter(this); messageText = s; /*8*/ Monitor::Pulse(this); Console::WriteLine("Set new message {0}", messageText); Monitor::Exit(this); } void ProcessMessages() { /*9*/ Monitor::Enter(this); while (true) { try { /*10*/ Monitor::Wait(this); } catch (ThreadInterruptedException^ e) { Console::WriteLine("ProcessMessage interrupted"); return; } Console::WriteLine("Processed new message {0}", messageText); } Monitor::Exit(this); } }; public ref class CreateMessages { MessageBuffer^ msg; public: CreateMessages(MessageBuffer^ m) { msg = m; } void CreateMessagesEntryPoint() { for (int i = 1; i <= 5; ++i) { msg->SetMessage(String::Concat("M-", i.ToString())); Thread::Sleep(2000); } Console::WriteLine("CreateMessages thread terminating"); } }; public ref class ProcessMessages { MessageBuffer^ msg; public: ProcessMessages(MessageBuffer^ m) { msg = m; } void ProcessMessagesEntryPoint() { msg->ProcessMessages(); Console::WriteLine("ProcessMessages thread terminating"); } }; |
在标记1中,创建一个MessageBuffer类型的共享缓冲区;接着在标记2a、2b、2c中,创建了一个线程用于处理放置于缓冲区中的每条信息;标记3a、3b和3c,也创建了一个线程,并在共享缓冲区中放置了连续的5条信息以便处理。这两个线程已被同步,因此处理者线程必须等到有"东西"放入到缓冲区中,才可以进行处理,且在前一条信息被处理完之前,不能放入第二条信息。在标记4中,将一直等待,直到创建者线程完成它的工作。
| Set new message M-1 Processed new message M-1 Set new message M-2 Processed new message M-2 Set new message M-3 Processed new message M-3 Set new message M-4 Processed new message M-4 Set new message M-5 Processed new message M-5 CreateMessages thread terminating ProcessMessage interrupted ProcessMessages thread terminating Primary thread terminating |
请仔细留意,处理者线程启动于创建者线程之前。如果以相反的顺序启动,将会在没有处理者线程等待的情况下,添加第一条信息,此时,没有可供唤醒处理者线程,当处理者线程运行到它的第一个函数调用Wait时,将会错过第一条信息,且只会在第二条信息存储时被唤醒。
管理线程
默认情况下,如果一个线程是前台线程,它将会一直执行下去,直到进入点函数结束,而不管它父类的生命期是多久;而在另一方面,后台线程则会在父类线程结束时自动结束。可通过设置Thread的IsBackground属性,把一个线程配置为后台线程,用同样的方法,也可把一个后台线程配置为前台线程。
一旦线程被启动,它即为活跃线程,可通过检查Thread的IsAlive属性来判断一个线程是否为活跃线程;通过调用Wait函数,并传递给它一个零毫秒,可使一个线程放弃剩余的CPU时间片;另外,线程还可通过CurrentThread::Thread::CurrentThread属性得到其自己的Thread对象。
每个线程都有与之相关的优先级,运行时环境(即操作系统)通过它来调度线程的执行,可通过
【中国下载站】【设为主页】【收藏本页】【打印本文】【回到顶部】【关闭此页】