Welcome to mirror list, hosted at ThFree Co, Russian Federation.

condition.cpp « base - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e2a60f07534d9fe0c7c44dfbeea94d75ec96f521 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include "base/condition.hpp"
#include "base/mutex.hpp"

#include "std/target_os.hpp"

#include <pthread.h>

#include <cerrno>
#include <cstdint>
#include <limits>

#include <sys/time.h>

namespace threads
{
  namespace impl
  {
    class ConditionImpl
    {
    public:
      Mutex m_Mutex;
      pthread_cond_t m_Condition;
    };
  }

  Condition::Condition() : m_pImpl(new impl::ConditionImpl())
  {
    ::pthread_cond_init(&m_pImpl->m_Condition, 0);
  }

  Condition::~Condition()
  {
    ::pthread_cond_destroy(&m_pImpl->m_Condition);
    delete m_pImpl;
  }

  void Condition::Signal(bool broadcast)
  {
    if (broadcast)
      ::pthread_cond_broadcast(&m_pImpl->m_Condition);
    else
      ::pthread_cond_signal(&m_pImpl->m_Condition);
  }

  void Condition::Wait()
  {
    ::pthread_cond_wait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex);
  }

  bool Condition::Wait(unsigned ms)
  {
    if (ms == std::numeric_limits<unsigned>::max())
    {
      Wait();
      return false;
    }

    ::timeval curtv;
    ::gettimeofday(&curtv, 0);

    ::timespec ts;

    uint64_t deltaNanoSec = curtv.tv_usec * 1000 + ms * 1000000;

    ts.tv_sec = curtv.tv_sec + deltaNanoSec / 1000000000;
    ts.tv_nsec = deltaNanoSec % 1000000000;

    int res = ::pthread_cond_timedwait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex, &ts);

    return (res == ETIMEDOUT);
  }

  void Condition::Lock()
  {
    m_pImpl->m_Mutex.Lock();
  }

  bool Condition::TryLock()
  {
    return m_pImpl->m_Mutex.TryLock();
  }

  void Condition::Unlock()
  {
    m_pImpl->m_Mutex.Unlock();
  }
}

namespace threads
{
  ConditionGuard::ConditionGuard(Condition & condition)
    : m_Condition(condition)
  {
    m_Condition.Lock();
  }

  ConditionGuard::~ConditionGuard()
  {
    m_Condition.Unlock();
  }

  void ConditionGuard::Wait(unsigned ms)
  {
    m_Condition.Wait(ms);
  }

  void ConditionGuard::Signal(bool broadcast)
  {
    m_Condition.Signal(broadcast);
  }
}