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