« C++Builder2009のスレッドの基本的な使い方のまとめ | メイン | Guarded Suspensionパターン »

Single Threaded Executionパターン

増補改訂版 Java言語で学ぶデザインパターン入門 マルチスレッド編』にある 「Single Threaded Executionパターン」をC++ Builder 2009で実装してみました。

C++BuilderにはJavaのsynchronizedがないため、 クリティカルセクション(TCriticalSectionクラス)と Before/Afterパターンを使って実装しました。

プログラムの意味は『増補改訂版 Java言語で学ぶデザインパターン入門 マルチスレッド編』をご覧下さい。

//スレッドセーフな出力
std::unique_ptr<TCriticalSection> CriticalSection(new TCriticalSection);
void Print(const std::string& S)
{
  CriticalSection->Acquire();
  std::cout << S << std::endl;
  CriticalSection->Release();
}
//スレッドセーフなTGateクラス
class TGate
{
public:
  TGate() : FCounter(0), FName("Nobody"), FAddress("Nowhere"), FCriticalSection(new TCriticalSection) {};
  void Pass(const std::string& Name, const std::string& Address)
  {
    FCriticalSection->Acquire();
    try
    {
    this->FCounter++;
      this->FName = Name;
      this->FAddress = Address;
      Check();
    }
    __finally
    {
      FCriticalSection->Release();
    }
  };
private:
  int FCounter;
  std::string FName;
  std::string FAddress;
  std::unique_ptr<TCriticalSection> FCriticalSection;
  void Check()
  {
    if (FName[0] != FAddress[0])
    {
      boost::format formater("***** BROKEN ***** No.%d : %s, %s");
      formater % FCounter % FName % FAddress;
      Print(formater.str());
    }
  };
};
//ひたすら門を通り続ける人を表すクラス
class TUserThread : public TThread
{
public:
  __fastcall TUserThread(TGate* Gate, std::string Name, std::string Address)
    : TThread(false), FGate(Gate), FName(Name), FAddress(Address) {};
protected:
  void __fastcall Execute()
  {
    Print(FName + " BEGIN");
    while (true)
    {
      FGate->Pass(FName, FAddress);
    }
  }
private:
  TGate* FGate;
  std::string FName;
  std::string FAddress;
};

int _tmain(int argc, _TCHAR* argv[])
{
  TGate* gate = new TGate();
  new TUserThread(gate, "Alice", "Alaska");
  new TUserThread(gate, "Bobby", "Brazil");
  new TUserThread(gate, "Chris", "Canada");

  Sleep(INFINITE);
  return 0;
}

トラックバック

このエントリーのトラックバックURL:
http://www.gesource.jp/mt/mt-tb.cgi/883

コメントを投稿

(いままで、ここでコメントしたことがないときは、コメントを表示する前にこのブログのオーナーの承認が必要になることがあります。承認されるまではコメントは表示されません。そのときはしばらく待ってください。)

About

2009年01月21日 13:59に投稿されたエントリーのページです。

ひとつ前の投稿は「C++Builder2009のスレッドの基本的な使い方のまとめ」です。

次の投稿は「Guarded Suspensionパターン」です。

他にも多くのエントリーがあります。メインページアーカイブページも見てください。

Powered by
Movable Type 3.35