summaryrefslogtreecommitdiff
path: root/server/src/mutex.cc
diff options
context:
space:
mode:
Diffstat (limited to 'server/src/mutex.cc')
-rw-r--r--server/src/mutex.cc76
1 files changed, 72 insertions, 4 deletions
diff --git a/server/src/mutex.cc b/server/src/mutex.cc
index 2cc75cc..ec0d0e8 100644
--- a/server/src/mutex.cc
+++ b/server/src/mutex.cc
@@ -37,21 +37,89 @@ Mutex::~Mutex()
pthread_mutex_destroy(&mutex);
}
+bool Mutex::trylock()
+{
+ return pthread_mutex_trylock(&mutex) == 0;
+}
+
void Mutex::lock()
{
- pthread_mutex_lock( &mutex );
+ pthread_mutex_lock(&mutex);
}
void Mutex::unlock()
{
- pthread_mutex_unlock( &mutex );
+ pthread_mutex_unlock(&mutex);
+}
+
+
+MutexAutolock::MutexAutolock(Mutex &m)
+ : mutex(m)
+{
+ mutex.lock();
+}
+
+MutexAutolock::~MutexAutolock()
+{
+ mutex.unlock();
}
#ifdef TEST_MUTEX
+//deps:
+//cflags: $(PTHREAD_CFLAGS)
+//libs: $(PTHREAD_LIBS)
+#include <test.h>
-int main()
+#include <unistd.h>
+
+volatile int cnt = 0;
+
+static void* thread_run(void *data)
{
- return 0;
+ Mutex *mutex = (Mutex*)data;
+ mutex->lock();
+ cnt++;
+ mutex->unlock();
+ return NULL;
}
+TEST_BEGIN;
+
+Mutex mutex;
+
+mutex.lock();
+TEST_FALSE(mutex.trylock(), "Testing if trylock works negative.");
+mutex.unlock();
+TEST_TRUE(mutex.trylock(), "Testing if trylock works positive.");
+mutex.unlock();
+
+mutex.lock();
+
+pthread_attr_t attr;
+pthread_t tid;
+pthread_attr_init(&attr);
+pthread_create(&tid, &attr, thread_run, &mutex);
+
+sleep(1);
+TEST_EQUAL_INT(cnt, 0, "Testing if lock prevent cnt from increasing.");
+mutex.unlock();
+
+sleep(1);
+TEST_EQUAL_INT(cnt, 1, "Testing if unlock makes cnt increase.");
+
+pthread_join(tid, NULL);
+pthread_attr_destroy(&attr);
+
+{
+ TEST_TRUE(mutex.trylock(), "Testing if autolock has not yet locked the mutex.");
+ mutex.unlock();
+ MutexAutolock mlock(mutex);
+ TEST_FALSE(mutex.trylock(), "Testing if autolock worked.");
+}
+
+TEST_TRUE(mutex.trylock(), "Testing if autolock has released the lock on the mutex.");
+mutex.unlock();
+
+TEST_END;
+
#endif/*TEST_MUTEX*/