-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.cpp
More file actions
84 lines (76 loc) · 1.45 KB
/
mutex.cpp
File metadata and controls
84 lines (76 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "postal.h"
#include "mutex.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
Mutex::Mutex( bool
#ifdef LINUX_PTHREAD
fastMutex
#endif
)
{
int rc;
#ifdef LINUX_PTHREAD
if ( !fastMutex ) {
pthread_mutexattr_t attr;
pthread_mutexattr_init( &attr );
rc = pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
if ( !rc ) {
rc = pthread_mutex_init( &m_mut, &attr );
}
pthread_mutexattr_destroy( &attr );
}else
#endif
{
rc = pthread_mutex_init( &m_mut, NULL );
}
if ( rc ) {
fprintf( stderr, "Can't create mutex.\n" );
exit( 1 );
}
}
Mutex::~Mutex( )
{
pthread_mutex_destroy( &m_mut );
}
int
Mutex::get_mutex( bool block )
{
if ( block ) {
if ( pthread_mutex_lock( &m_mut )) {
return( -1 );
}
}else {
if ( pthread_mutex_trylock( &m_mut )) {
return( -1 );
}
}
return( 0 );
}
int
Mutex::put_mutex( )
{
if ( pthread_mutex_unlock( &m_mut )) {
return( -1 );
}
return( 0 );
}
Lock::Lock( Mutex &mut )
: m_mut( mut )
{
if ( m_mut.get_mutex( )) {
perror( "" );
fprintf( stderr, "Can't lock mutex.\n" );
exit( 1 );
}
}
Lock::~Lock( )
{
if ( m_mut.put_mutex( )) {
fprintf( stderr, "Can't unlock mutex.\n" );
exit( 1 );
}
}