The equivalent to pthread_mutex_t in Windows is a CriticalSection (fast mutex, not nestable, one process only) or a Mutex (processes and threads, nestable).
With both you could control an arbitrary resource, so that only one thread has exclusive access and all others that try to access while the resource is exclusively locked have to wait til unlock:
#ifdef PTHREAD
# include <pthread.h>
/*
* thread and mutex types
*/
typedef pthread_t Thread;
typedef pthread_mutex_t ThreadMutex;
#elif defined (WIN32)
typedef unsigned long Thread;
typedef CRITICAL_SECTION ThreadMutex;
#endif
/* one time initialization of a 'fast' mutex (not reversible) */
void initMutex(void* pMutex)
{
#if defined (PTHREAD)
pthread_mutex_init((pthrea
#elif defined (WIN32)
InitializeCriticalSection(
#endif
}
/* enter critical section and block others threads or wait */
void enterMutex(void* pMutex)
{
#if defined (PTHREAD)
pthread_mutex_lock((pthrea
#elif defined (WIN32)
EnterCriticalSection((PCRI
#endif
}
/* leave critical section and release any other thread blocked */
void leaveMutex(void* pMutex)
{
#if defined (PTHREAD)
pthread_mutex_unlock((pthr
#elif defined (WIN32)
LeaveCriticalSection((PCRI
#endif
}
You would use this like:
ThreadMutex mutex; // create global mutex
int main()
{
initMutex(&mutex);
// start some threads ...
while (true)
{
doSomething();
if (needToWriteToLogFile())
{
// either we get the resource (logfile) exclusively or we have to wait
enterMutex(&mutex);
ofstream oflog("logfile.log", ios::append | ios::out);
writeLog(oflog, "Any message");
oflog.close();
leaveMutex(&mutex);
}
}
}
// thread.cpp
void threadFunction(void* pParam)
{
while (true)
{
doSomeThreadThings();
if (needToWriteToLogFile())
{
// either we get the resource (logfile) exclusively or we have to wait
enterMutex(&mutex);
ofstream oflog("logfile.log", ios::append | ios::out);
writeLog(oflog, "Any message");
oflog.close();
leaveMutex(&mutex);
}
}
}
Regards, Alex
Main Topics
Browse All Topics





by: AxterPosted on 2005-04-10 at 23:00:14ID: 13750599
Can you show an example as to how you're using WaitForMultipleObjects?
I'm sure there's a way to duplicate the logic requirements using POSIX functions.