程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> VC >> vc教程 >> 實例解析C++/CLI線程之線程狀態持久性

實例解析C++/CLI線程之線程狀態持久性

編輯:vc教程

其他形式的同步

我們可使用類Monitor與類Thread中的某些函數,直接控制線程的同步,請看例1。

例1:

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. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved