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_SINGLE_EXECUTOR 00022 #define AMINO_UTIL_SINGLE_EXECUTOR 00023 00024 #include <pthread.h> 00025 #include <string> 00026 #include <stdio.h> 00027 #include <memory> 00028 00029 #include <amino/thread.h> 00030 #include <amino/condition.h> 00031 #include <amino/mutex.h> 00032 #include <amino/lock.h> 00033 #include <amino/exec_serv.h> 00034 #include <amino/cstdatomic> 00035 #include <amino/future.h> 00036 #include <amino/ftask.h> 00037 00038 namespace amino { 00039 using namespace std; 00040 00044 class SingleExecutor:public ExecutorService{ 00045 private: 00046 volatile int fTasks; 00047 public: 00048 SingleExecutor(){ 00049 fTasks = 0; 00050 fShutdown= false; 00051 } 00052 00053 virtual ~SingleExecutor(){ 00054 } 00055 00061 void execute(Runnable* task){ 00062 unique_lock<mutex> llock(f_mutex_finish); 00063 if(fShutdown) 00064 throw std::logic_error("Already shutdown!\n"); 00065 fTasks++; 00066 llock.unlock(); 00067 00068 task->run(); 00069 00070 llock.lock(); 00071 fTasks--; 00072 if(fTasks==0) 00073 condFinish.notify_all(); 00074 llock.unlock(); 00075 } 00076 00086 auto_ptr<Future> submit(Runnable* task){ 00087 FutureTask * ft = new FutureTask(task); 00088 execute(ft); 00089 00090 auto_ptr<Future> pFuture(ft); 00091 00092 return pFuture; 00093 } 00094 00100 virtual void shutdown(){ 00101 unique_lock<mutex> llock(f_mutex_finish); 00102 fShutdown= true; 00103 llock.unlock(); 00104 } 00105 00106 virtual void halt(){ 00107 unique_lock<mutex> llock(f_mutex_finish); 00108 fShutdown= true; 00109 llock.unlock(); 00110 } 00111 protected: 00112 virtual bool finished(){ 00113 return fTasks==0; 00114 } 00115 }; 00116 } 00117 #endif