a5b8a0c5bb5eeff6c2d5778135e07af1ab77bead
[platform/upstream/iotivity.git] / service / resource-manipulation / modules / common / expiryTimer / src / ExpiryTimer_Impl.h
1 //******************************************************************
2 //
3 // Copyright 2015 Samsung Electronics All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #ifndef _EXPIRY_TIMER_Impl_H_
22 #define _EXPIRY_TIMER_Impl_H_
23
24 // CHECKER_WAIT_TIME : checker thread waits new request for 10000 seconds
25 #define CHECKER_WAIT_TIME 10000
26
27 #include <iostream>
28 #include <functional>
29 #include <map>
30 #include <mutex>
31 #include <thread>
32 #include <chrono>
33 #include <condition_variable>
34
35 class ExpiryTimer_Impl
36 {
37 public:
38     typedef unsigned int Id;
39     typedef std::function<void*(Id)> TimerCb;
40
41     typedef long long DelayMilliSec;
42     typedef std::chrono::milliseconds milliSeconds;
43     typedef std::chrono::duration<int64_t, std::milli> milliDelayTime;
44     typedef std::chrono::duration<int64_t, std::milli> ExpiredTime;
45
46 private:
47     struct TimerCBInfo
48     {
49         Id m_id;
50         TimerCb m_cb;
51     };
52
53 public:
54    ~ExpiryTimer_Impl();
55
56 private:
57    ExpiryTimer_Impl();
58
59 public:
60     static ExpiryTimer_Impl* getInstance();
61
62     Id postTimer(DelayMilliSec, TimerCb);
63     bool cancelTimer(Id);
64
65 private:
66    Id generateID();
67
68    void insertTimerCBInfo(ExpiredTime, TimerCb ,Id);
69    ExpiredTime countExpireTime(milliSeconds);
70
71    void createChecker();
72    void doChecker();
73
74    void doExecutor(ExpiredTime);
75
76 private:
77    static ExpiryTimer_Impl* s_instance;
78    static std::once_flag mflag;
79
80    std::multimap<ExpiredTime, TimerCBInfo> mTimerCBList;
81
82    std::thread check;
83    std::mutex m_mutex;
84    std::mutex cond_mutex;
85    std::condition_variable m_cond;
86
87 public:
88    class ExecutorThread
89    {
90    public:
91        ExecutorThread(TimerCBInfo);
92        ~ExecutorThread();
93
94    public:
95        void executorFunc(TimerCBInfo);
96
97    private:
98        std::thread execute;
99    };
100 };
101
102 #endif //_EXPIRY_TIMER_Impl_H_