Files
winix/core/synchro.cpp
Tomasz Sowa 222955a2e7 fixed: in Synchro: we should have a table (map) of reference counters
each one for each thread
fixed: on Linux: pthread mutexes by default behaves differently than on FreeBSD
       we have to set PTHREAD_MUTEX_ERRORCHECK attribute 
       when creating a mutex
       



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@953 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-02-14 11:20:22 +00:00

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