Remove de-funct Bullet dynamics plugin
[platform/core/uifw/dali-adaptor.git] / adaptors / base / conditional-wait.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
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
18 // CLASS HEADER
19 #include "conditional-wait.h"
20
21 // EXTERNAL INCLUDES
22 #include <pthread.h>
23
24 namespace Dali
25 {
26
27 namespace Internal
28 {
29
30 namespace Adaptor
31 {
32
33 namespace
34 {
35 } // unnamed namespace
36
37 struct ConditionalWait::ConditionalWaitImpl
38 {
39   pthread_mutex_t mutex;
40   pthread_cond_t condition;
41   volatile unsigned int count;
42 };
43
44 ConditionalWait::ConditionalWait()
45 : mImpl( new ConditionalWaitImpl )
46 {
47   pthread_mutex_init( &mImpl->mutex, NULL );
48   pthread_cond_init( &mImpl->condition, NULL );
49   mImpl->count = 0;
50 }
51
52 ConditionalWait::~ConditionalWait()
53 {
54   pthread_cond_destroy( &mImpl->condition );
55   pthread_mutex_destroy( &mImpl->mutex );
56   delete mImpl;
57 }
58
59 void ConditionalWait::Notify()
60 {
61   // pthread_cond_wait requires a lock to be held
62   pthread_mutex_lock( &mImpl->mutex );
63   volatile unsigned int previousCount = mImpl->count;
64   mImpl->count = 0; // change state before broadcast as that may wake clients immediately
65   // broadcast does nothing if the thread is not waiting but still has a system call overhead
66   // broadcast all threads to continue
67   if( 0 != previousCount )
68   {
69     pthread_cond_broadcast( &mImpl->condition );
70   }
71   pthread_mutex_unlock( &mImpl->mutex );
72 }
73
74 void ConditionalWait::Wait()
75 {
76   // pthread_cond_wait requires a lock to be held
77   pthread_mutex_lock( &mImpl->mutex );
78   ++(mImpl->count);
79   // pthread_cond_wait may wake up without anyone calling Notify
80   do
81   {
82     // wait while condition changes
83     pthread_cond_wait( &mImpl->condition, &mImpl->mutex ); // releases the lock whilst waiting
84   }
85   while( 0 != mImpl->count );
86   // when condition returns the mutex is locked so release the lock
87   pthread_mutex_unlock( &mImpl->mutex );
88 }
89
90 unsigned int ConditionalWait::GetWaitCount() const
91 {
92   return mImpl->count;
93 }
94
95 } // namespace Adaptor
96
97 } // namespace Internal
98
99 } // namespace Dali