Update snapshot(2018-01-04)
[platform/upstream/iotivity.git] / examples / OICSensorBoard / observer.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Corporation.
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 #include "observer.h"
22
23 IoTObserver::IoTObserver(IoTObserverCb Cb) :
24         m_callback(Cb), m_destroy(false), m_started(false)
25 {
26     m_observerThread[0] = thread(&IoTObserver::observerThread, this);
27 }
28
29 IoTObserver::~IoTObserver()
30 {
31     terminate();
32 }
33
34 void IoTObserver::start()
35 {
36     if (!m_started)
37     {
38         {
39             lock_guard<mutex> lock(m_mutex);
40             m_started = true;
41         }
42         m_cond.notify_one();
43     }
44 }
45
46 void IoTObserver::stop()
47 {
48     m_started = false;
49 }
50
51 void IoTObserver::terminate()
52 {
53     m_destroy = true;
54     stop();
55     m_cond.notify_one();
56     m_observerThread[0].join();
57 }
58
59 void IoTObserver::observerThread()
60 {
61     while (!m_destroy)
62     {
63         unique_lock<mutex> lock(m_mutex);
64         if (!m_started)
65             m_cond.wait(lock);
66         while (m_started)
67         {
68             m_callback();
69         }
70     }
71 }