マルチスレッドの使用

1368 ワード

スレッドが実行されるクラスはNLMISC::Irunnableを継承する必要があります.このように見えます.
class CTaskThread : public NLMISC::IRunnable
{
	void run()
	{
		while(true)
		{
			NLMISC::nlSleep(0);
		}
	}
};

run()は再実装が必要なインタフェースであり,スレッドが実際に実行する内容である.
このスレッドを起動するのも簡単です.
	IThread *thread = IThread::create (new CTaskThread);
	thread->start ();

通常、1つのスレッドの実行には、いくつかのパラメータが必要になるか、古典的な生産者->消費者モデルなどの外部とデータを交換する必要があります.
パラメータの入力により、このクラスに初期化関数を追加できます.
bool CMysqlRunCallback::init( const std::string &hostName, const std::string &userName, const std::string &password, const std::string &defaultDatabase)
{
	_runCallbackThread.connectDB(hostName,userName,password,defaultDatabase);
	_thread = NLMISC::IThread::create (&_runCallbackThread);
	_thread->start ();
	return true;
}

一方、交換データはCBufFIFOringまたはCBufFIFO 2を使用することができる.
class RunCallbackThread : public NLMISC::IRunnable
{
public:
	bool pushEvent( CQueryEvent* sql_event )    { return _SQLQueryPool.push_back(sql_event); }
	CQueryEvent* getSQLReturn()                 { return _SQLReturnPool.pop_front();         }

private:
	NLMISC::CBufFIFORing<CQueryEvent>      _SQLQueryPool;
	NLMISC::CBufFIFORing<CQueryEvent>      _SQLReturnPool;

	void run ();
};