1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (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://www.apache.org/licenses/LICENSE-2.0
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 #include <pthread.h>
18 
19 #ifndef __WIFI_HAL_SYNC_H__
20 #define __WIFI_HAL_SYNC_H__
21 
22 class Mutex
23 {
24 private:
25     pthread_mutex_t mMutex;
26 public:
Mutex()27     Mutex() {
28         pthread_mutex_init(&mMutex, NULL);
29     }
~Mutex()30     ~Mutex() {
31         pthread_mutex_destroy(&mMutex);
32     }
tryLock()33     int tryLock() {
34         return pthread_mutex_trylock(&mMutex);
35     }
lock()36     int lock() {
37         return pthread_mutex_lock(&mMutex);
38     }
unlock()39     void unlock() {
40         pthread_mutex_unlock(&mMutex);
41     }
42 };
43 
44 class Condition
45 {
46 private:
47     pthread_cond_t mCondition;
48     pthread_mutex_t mMutex;
49 
50 public:
Condition()51     Condition() {
52         pthread_mutex_init(&mMutex, NULL);
53         pthread_cond_init(&mCondition, NULL);
54     }
~Condition()55     ~Condition() {
56         pthread_cond_destroy(&mCondition);
57         pthread_mutex_destroy(&mMutex);
58     }
59 
wait()60     int wait() {
61         return pthread_cond_wait(&mCondition, &mMutex);
62     }
63 
wait(struct timespec abstime)64     int wait(struct timespec abstime)
65     {
66         struct timeval now;
67 
68         gettimeofday(&now,NULL);
69 
70         abstime.tv_sec += now.tv_sec;
71         if(((abstime.tv_nsec + now.tv_usec*1000) > 1000*1000*1000) || (abstime.tv_nsec + now.tv_usec*1000 < 0))
72         {
73            abstime.tv_sec += 1;
74            abstime.tv_nsec += now.tv_usec * 1000;
75            abstime.tv_nsec -= 1000*1000*1000;
76         }
77         else
78         {
79             abstime.tv_nsec += now.tv_usec * 1000;
80         }
81         return pthread_cond_timedwait(&mCondition, &mMutex, &abstime);
82     }
83 
signal()84     void signal() {
85         pthread_cond_signal(&mCondition);
86     }
87 };
88 
89 #endif
90