1 // Copyright (c) 2012-2014 Konstantin Isakov <ikm@zbackup.org> and ZBackup contributors, see CONTRIBUTORS
2 // Part of ZBackup. Licensed under GNU GPLv2 or later + OpenSSL, see LICENSE
3
4 #include "mt.hh"
5
6 #include <unistd.h>
7 #include "check.hh"
8
Mutex()9 Mutex::Mutex()
10 {
11 pthread_mutex_init( &mutex, 0 );
12 }
13
lock()14 void Mutex::lock()
15 {
16 pthread_mutex_lock( &mutex );
17 }
18
unlock()19 void Mutex::unlock()
20 {
21 pthread_mutex_unlock( &mutex );
22 }
23
~Mutex()24 Mutex::~Mutex()
25 {
26 pthread_mutex_destroy( &mutex );
27 }
28
Condition()29 Condition::Condition()
30 {
31 pthread_cond_init( &cond, 0 );
32 }
33
signal()34 void Condition::signal()
35 {
36 pthread_cond_signal( &cond );
37 }
38
broadcast()39 void Condition::broadcast()
40 {
41 pthread_cond_broadcast( &cond );
42 }
43
wait(Mutex & m)44 void Condition::wait( Mutex & m )
45 {
46 pthread_cond_wait( &cond, &m.mutex );
47 }
48
~Condition()49 Condition::~Condition()
50 {
51 pthread_cond_destroy( &cond );
52 }
53
__thread_routine(void * param)54 void * Thread::__thread_routine( void * param )
55 {
56 return ( (Thread *)param ) -> threadFunction();
57 }
58
start()59 void Thread::start()
60 {
61 ZBACKUP_CHECK( pthread_create( &thread, 0, &__thread_routine, this ) == 0,
62 "pthread_create() failed" );
63 }
64
detach()65 void Thread::detach()
66 {
67 ZBACKUP_CHECK( pthread_detach( thread ) == 0, "pthread_detach() failed" );
68 }
69
join()70 void * Thread::join()
71 {
72 void * ret;
73 pthread_join( thread, &ret );
74 return ret;
75 }
76
getNumberOfCpus()77 size_t getNumberOfCpus()
78 {
79 long result = sysconf( _SC_NPROCESSORS_ONLN );
80
81 // Handle -1 and also sanitize the 0 value which wouldn't make sense
82 return result < 1 ? 1 : result;
83 }
84