winix/core/synchro.cpp

83 lines
1.0 KiB
C++
Executable File

/*
* This file is a part of Winix
* and is not publicly distributed
*
* Copyright (c) 2010-2014, Tomasz Sowa
* All rights reserved.
*
*/
#include <errno.h>
#include "synchro.h"
namespace Winix
{
Synchro::Synchro()
{
was_stop_signal = false;
#ifdef __FreeBSD__
/*
* on FreeBSD a pthread's pthread_mutex_lock() is checking for deadlocks by default
*/
mutex = PTHREAD_MUTEX_INITIALIZER;
#else
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
#endif
}
bool Synchro::Lock()
{
int res = pthread_mutex_lock(&mutex);
if( res == 0 )
{
ref[pthread_self()] = 1;
return true;
}
else
if( res == EDEADLK )
{
// Lock() method in this thread was called before
ref[pthread_self()] += 1;
return true;
}
return false;
}
void Synchro::Unlock()
{
int & r = ref[pthread_self()];
if( r > 1 )
{
r -= 1;
}
else
if( r == 1 )
{
pthread_mutex_unlock(&mutex);
}
}
} // namespace Winix