Change license to APLv2.0
[platform/core/messaging/msg-service.git] / include / utils / MsgMutex.h
1 /*
2  * msg-service
3  *
4  * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd. All rights reserved
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18 */
19
20 #ifndef __MSG_MUTEX_H__
21 #define __MSG_MUTEX_H__
22
23 /*==================================================================================================
24                                          INCLUDE FILES
25 ==================================================================================================*/
26 #include <iostream>
27 #include <pthread.h>
28 #include <sys/time.h>
29 #include <time.h>
30
31 using namespace std;
32
33 int GetMsgReady();
34 void WaitMsgReady(int sec);
35
36 class Mutex
37 {
38 public:
39         Mutex(){ pthread_mutex_init(&m, 0); }
40         void lock(){ pthread_mutex_lock(&m); }
41         void unlock(){ pthread_mutex_unlock(&m); }
42         pthread_mutex_t* pMutex() { return &m; }
43
44 private:
45         pthread_mutex_t m;
46 };
47
48 class MutexLocker
49 {
50 public:
51         MutexLocker(Mutex& mx)
52         {
53                 pm = &mx;
54                 pm->lock();
55         }
56
57         ~MutexLocker()
58         {
59                 pm->unlock();
60         }
61
62 private:
63         Mutex *pm;
64 };
65
66 class CndVar
67 {
68 public:
69         CndVar(){ pthread_cond_init(&c, 0); }
70         void wait(pthread_mutex_t* m) { pthread_cond_wait(&c, m); }
71         int timedwait(pthread_mutex_t* m, int sec)
72         {
73                 struct timeval now = {0};
74                 struct timespec timeout = {0};
75                 gettimeofday(&now, NULL);
76                 timeout.tv_sec = now.tv_sec+sec;
77                 timeout.tv_nsec = now.tv_usec;
78                 int retcode = pthread_cond_timedwait(&c, m, &timeout);
79                 return retcode;
80         }
81         void signal(){ pthread_cond_signal(&c); }
82         void broadcast(){ pthread_cond_broadcast(&c); }
83
84 private:
85         pthread_cond_t c;
86 };
87
88 #endif //__MUTEX_H__
89