2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "conditional-wait.h"
35 } // unnamed namespace
37 struct ConditionalWait::ConditionalWaitImpl
39 pthread_mutex_t mutex;
40 pthread_cond_t condition;
44 ConditionalWait::ConditionalWait()
45 : mImpl( new ConditionalWaitImpl )
47 pthread_mutex_init( &mImpl->mutex, NULL );
48 pthread_cond_init( &mImpl->condition, NULL );
52 ConditionalWait::~ConditionalWait()
54 pthread_cond_destroy( &mImpl->condition );
55 pthread_mutex_destroy( &mImpl->mutex );
59 void ConditionalWait::Notify()
61 // pthread_cond_wait requires a lock to be held
62 pthread_mutex_lock( &mImpl->mutex );
63 bool wasWaiting = mImpl->wait;
65 pthread_mutex_unlock( &mImpl->mutex );
66 // broadcast does nothing if the thread is not waiting but still has a system call overhead
67 // broadcast all threads to continue
70 pthread_cond_broadcast( &mImpl->condition );
74 void ConditionalWait::Wait()
76 // pthread_cond_wait requires a lock to be held
77 pthread_mutex_lock( &mImpl->mutex );
79 // pthread_cond_wait may wake up without anyone calling Notify
82 // wait while condition changes
83 pthread_cond_wait( &mImpl->condition, &mImpl->mutex ); // releases the lock whilst waiting
85 // when condition returns the mutex is locked so release the lock
86 pthread_mutex_unlock( &mImpl->mutex );
89 bool ConditionalWait::IsWaiting() const
91 bool isWaiting( false );
92 pthread_mutex_lock( &mImpl->mutex );
93 isWaiting = mImpl->wait;
94 pthread_mutex_unlock( &mImpl->mutex );
100 } // namespace Adaptor
102 } // namespace Internal