"Fossies" - the Fresh Open Source Software Archive 
Member "postal-0.76/mutex.cpp" (14 Jan 2003, 1233 Bytes) of package /linux/privat/postal-0.76.tgz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style:
standard) with prefixed line numbers and
code folding option.
Alternatively you can here
view or
download the uninterpreted source code file.
For more information about "mutex.cpp" see the
Fossies "Dox" file reference documentation.
1 #ifndef _GNU_SOURCE
2 #define _GNU_SOURCE
3 #endif
4
5 #include "postal.h"
6 #include "mutex.h"
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <stdlib.h>
10
11 Mutex::Mutex(bool
12 #ifdef LINUX_PTHREAD
13 fastMutex
14 #endif
15 )
16 {
17 int rc;
18 #ifdef LINUX_PTHREAD
19 if(!fastMutex)
20 {
21 pthread_mutexattr_t attr;
22 pthread_mutexattr_init(&attr);
23 rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
24 if(!rc)
25 rc = pthread_mutex_init(&m_mut, &attr);
26 pthread_mutexattr_destroy(&attr);
27 }
28 else
29 #endif
30 {
31 rc = pthread_mutex_init(&m_mut, NULL);
32 }
33 if(rc)
34 {
35 fprintf(stderr, "Can't create mutex.\n");
36 exit(1);
37 }
38 }
39
40 Mutex::~Mutex()
41 {
42 pthread_mutex_destroy(&m_mut);
43 }
44
45 int Mutex::get_mutex(bool block)
46 {
47 if(block)
48 {
49 if(pthread_mutex_lock(&m_mut))
50 return -1;
51 }
52 else
53 {
54 if(pthread_mutex_trylock(&m_mut))
55 return -1;
56 }
57 return 0;
58 }
59
60 int Mutex::put_mutex()
61 {
62 if(pthread_mutex_unlock(&m_mut))
63 return -1;
64 return 0;
65 }
66
67 Lock::Lock(Mutex &mut)
68 : m_mut(mut)
69 {
70 if(m_mut.get_mutex())
71 {
72 perror("");
73 fprintf(stderr, "Can't lock mutex.\n");
74 exit(1);
75 }
76 }
77
78 Lock::~Lock()
79 {
80 if(m_mut.put_mutex())
81 {
82 fprintf(stderr, "Can't unlock mutex.\n");
83 exit(1);
84 }
85 }