//------------------------------------------------------------------------------
// Lamp : Open source game middleware
// Copyright (C) 2004  Junpei Ohtani ( Email : junpee@users.sourceforge.jp )
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//------------------------------------------------------------------------------

/** @file
 * クリティカルセクションヘッダ
 * @author Junpee
 */

#ifndef CRITICAL_SECTION_H_
#define CRITICAL_SECTION_H_

#include <Core/Thread/LockObject.h>

namespace Lamp{

//------------------------------------------------------------------------------
/**
 * クリティカルセクション
 */
class CriticalSection : public LockObject{
public:
	/**
	 * コンストラクタ
	 */
	CriticalSection() : lockCount_(0), threadID_(invalidThreadID){
		::InitializeCriticalSection(&criticalSection_);
	}

	/**
	 * デストラクタ
	 */
	virtual ~CriticalSection(){
		Assert(threadID_ == invalidThreadID);
		Assert(lockCount_ == 0);
		::DeleteCriticalSection(&criticalSection_);
	}

	/**
	 * ロック
	 */
	virtual void lock(){
		::EnterCriticalSection(&criticalSection_);
		lockCount_++;
		threadID_ = ::GetCurrentThreadId();
	}

	/**
	 * アンロック
	 */
	virtual void unlock(){
		Assert(lockCount_ > 0);
		lockCount_--;
		if(lockCount_ == 0){ threadID_ = invalidThreadID; }
		::LeaveCriticalSection(&criticalSection_);
	}

	/**
	 * カレントスレッドによってロックされているか
	 * @return カレントスレッドによってロックされていればtrue
	 */
	virtual bool isLockedByCurrentThread() const{
		return (::GetCurrentThreadId() == threadID_);
	}

protected:
	/// クリティカルセクションメンバ
	CRITICAL_SECTION criticalSection_;
	/// ロックカウント
	int lockCount_;
	/// スレッドID
	u_int threadID_;

	/// 無効なスレッドID
	static const u_int invalidThreadID = 0xffffffff;

};

//------------------------------------------------------------------------------
} // End of namespace Lamp
#endif // End of CRITICAL_SECTION_H_
//------------------------------------------------------------------------------
