00001 /* 00002 * Scale Stack 00003 * 00004 * Copyright 2010 Eric Day 00005 * 00006 * Licensed under the Apache License, Version 2.0 (the "License"); 00007 * you may not use this file except in compliance with the License. 00008 * You may obtain a copy of the License at 00009 * 00010 * http://www.apache.org/licenses/LICENSE-2.0 00011 * 00012 * Unless required by applicable law or agreed to in writing, software 00013 * distributed under the License is distributed on an "AS IS" BASIS, 00014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00015 * See the License for the specific language governing permissions and 00016 * limitations under the License. 00017 */ 00018 00024 #include "config.h" 00025 00026 #include <algorithm> 00027 #include <exception> 00028 #include <functional> 00029 00030 #include <scalestack/event/libevent/handler_provider.h> 00031 #include <scalestack/event/libevent/service.h> 00032 #include <scalestack/event/libevent/thread.h> 00033 #include <scalestack/kernel/delete_pointer.h> 00034 #include <scalestack/kernel/module.h> 00035 #include <scalestack/kernel/option.h> 00036 00037 using namespace std; 00038 00039 namespace scalestack 00040 { 00041 namespace event 00042 { 00043 namespace libevent 00044 { 00045 00046 /* 00047 * Public methods. 00048 */ 00049 00050 service::service(kernel::module& module): 00051 event::service(module), 00052 _current_thread(), 00053 _threads() 00054 { 00055 size_t thread_count = _module.get_option("threads").get_size_value(); 00056 if (thread_count == 0) 00057 _module.log_fatal("The 'threads' option must be greater than 0"); 00058 00059 for (size_t thread_index = 0; thread_index < thread_count; thread_index++) 00060 { 00061 thread* thread = NULL; 00062 try 00063 { 00064 thread = new libevent::thread(_module, thread_index); 00065 _threads.push_back(thread); 00066 } 00067 catch (exception&) 00068 { 00069 if (thread != NULL) 00070 { 00071 thread->shutdown(); 00072 delete thread; 00073 } 00074 00075 _remove_threads(); 00076 throw; 00077 } 00078 } 00079 } 00080 00081 service::~service() 00082 { 00083 _remove_threads(); 00084 } 00085 00086 /* 00087 * Private methods. 00088 */ 00089 00090 event::handler_provider* service::_add_handler(handler* handler) 00091 { 00092 /* Choose assigned thread by round-robin. */ 00093 _current_thread++; 00094 return new handler_provider(_module, handler, 00095 *_threads[_current_thread % _threads.size()]); 00096 } 00097 00098 void service::_remove_threads(void) 00099 { 00100 for_each(_threads.begin(), _threads.end(), mem_fun(&thread::shutdown)); 00101 for_each(_threads.begin(), _threads.end(), kernel::delete_pointer()); 00102 } 00103 00104 } /* namespace libevent */ 00105 } /* namespace event */ 00106 } /* namespace scalestack */
1.6.3