#ifndef _BOOST_LITE_H #define _BOOST_LITE_H // light weigth version of boost objects #include #include #include namespace boost { struct win32_error { public: DWORD err; std::string name; win32_error(const std::string& name) : err(GetLastError()), name(name) { } ~win32_error() { printf("@%08lx win32 ERROR: %08lx - %s\n", GetTickCount(), err, name.c_str()); } }; template class unique_lock { public: unique_lock(T& mtx) : _mtx(mtx), _locked(false) { lock(); } ~unique_lock() { if (_locked) unlock(); } void unlock() { if (_locked) { _mtx.unlock(); _locked= false; } } void lock() { _mtx.lock(); _locked= true; } private: T &_mtx; bool _locked; }; class mutex { public: mutex() { InitializeCriticalSection(&_lock); } ~mutex() { DeleteCriticalSection(&_lock); } void lock() { EnterCriticalSection(&_lock); } void unlock() { LeaveCriticalSection(&_lock); } typedef unique_lock scoped_lock; private: CRITICAL_SECTION _lock; }; class condition { public: condition() { _sema= CreateSemaphore(0,0,LONG_MAX,0); if (_sema==NULL) throw win32_error("CreateSemaphore"); } ~condition() { CloseHandle(_sema); } void notify_one() { // this results in a ERROR_TOO_MANY_POSTS when more than maxcount // releases were invoked on this semaphore if (!ReleaseSemaphore(_sema, 1, NULL)) throw win32_error("ReleaseSemaphore"); } bool timed_wait(mutex::scoped_lock& lck, int timeout) { lck.unlock(); int rc= WaitForSingleObject(_sema, timeout); lck.lock(); if (rc==WAIT_OBJECT_0) return true; if (rc==WAIT_TIMEOUT) return false; throw win32_error("WaitForSingleObject"); } void wait(mutex::scoped_lock& lck) { lck.unlock(); int rc= WaitForSingleObject(_sema, INFINITE); lck.lock(); if (rc!=WAIT_OBJECT_0) throw win32_error("WaitForSingleObject"); } private: HANDLE _sema; }; struct thread_data_base { virtual void run()=0; }; class thread { template struct thread_data : thread_data_base { thread_data(T f) : _f(f) { } virtual void run() { _f(); } T _f; }; public: typedef DWORD id; id get_id() const { return _id; } /* thread() : _data(NULL), _h(0) { } */ template thread(T proc) : _data(new thread_data(proc)), _h(NULL), _id(0) { _h= CreateThread(0,0,&thread::staticproc, this, 0, &_id); if (_h==NULL) throw win32_error("CreateThread"); } ~thread() { if (_h) { TerminateThread(_h, 0); CloseHandle(_h); _h=0; delete _data; } } /* thread& operator=(thread& org) { _h= org._h; _data= org._data; org._h= 0; org._data= NULL; return *this; } */ static DWORD WINAPI staticproc(LPVOID self) { reinterpret_cast(self)->_data->run(); return 0; } void join() { WaitForSingleObject(_h,INFINITE); } public: thread_data_base *_data; HANDLE _h; DWORD _id; }; template struct thread::thread_data >: thread_data_base { thread_data(boost::reference_wrapper f) : _f(f) { } virtual void run() { _f(); } T& _f; }; } #endif