00001 /* 00002 * (c) Copyright 2008, IBM Corporation. 00003 * Licensed under the Apache License, Version 2.0 (the "License"); 00004 * you may not use this file except in compliance with the License. 00005 * You may obtain a copy of the License at 00006 * 00007 * http://www.apache.org/licenses/LICENSE-2.0 00008 * 00009 * Unless required by applicable law or agreed to in writing, software 00010 * distributed under the License is distributed on an "AS IS" BASIS, 00011 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 * See the License for the specific language governing permissions and 00013 * limitations under the License. 00014 * 00015 * Change History: 00016 * 00017 * yy-mm-dd Developer Defect Description 00018 * -------- --------- ------ ----------- 00019 * 08-08-04 ganzhi N/A Initial version 00020 */ 00021 #ifndef AMINO_UTIL_EXECUTOR_SERVICE 00022 #define AMINO_UTIL_EXECUTOR_SERVICE 00023 00024 #include <pthread.h> 00025 #include <string> 00026 #include <stdio.h> 00027 #include <time.h> 00028 #include <cassert> 00029 00030 #include <amino/thread.h> 00031 #include <amino/condition.h> 00032 #include <amino/mutex.h> 00033 #include <amino/lock.h> 00034 #include <amino/cstdatomic> 00035 00036 namespace amino{ 00037 00041 class ExecutorService{ 00042 protected: 00043 volatile bool fShutdown; 00044 condition_variable condFinish; 00045 recursive_mutex f_mutex_finish; 00046 void notify_finish(){ 00047 unique_lock<recursive_mutex> llock(f_mutex_finish); 00048 condFinish.notify_all(); 00049 } 00050 public: 00056 virtual void shutdown()=0; 00057 00064 virtual void halt()=0; 00065 00066 virtual bool finished()=0; 00067 00073 virtual void waitTermination(){ 00074 #ifdef DEBUG 00075 cout<<"Begin WaitTermination of ExecutorService\n"; 00076 #endif 00077 if(!fShutdown) 00078 throw std::logic_error( 00079 "Call shutdown()/halt() before wait " 00080 "termination of this executor!\n"); 00081 00082 unique_lock<recursive_mutex> llock(f_mutex_finish); 00083 00084 while(!finished()) 00085 condFinish.wait(llock); 00086 00087 #ifdef DEBUG 00088 assert(finished()); 00089 cout<<"Finish WaitTermination\n"; 00090 #endif 00091 return; 00092 } 00093 00104 virtual bool waitTermination(int timeOut){ 00105 if(!fShutdown) 00106 throw std::logic_error( 00107 "Call shutdown()/halt() before wait " 00108 "termination of this executor!\n"); 00109 00110 unique_lock<recursive_mutex> llock(f_mutex_finish); 00111 if(!finished()){ 00112 condFinish.timed_wait(llock, timeOut); 00113 00114 return finished(); 00115 } 00116 00117 return finished(); 00118 } 00119 }; 00120 } 00121 #endif