2 /* $Id: thread_pool_observer.cpp,v 1.15 2006-03-29 13:44:45 adam Exp $
3 Copyright (c) 2005-2006, Index Data.
17 #include <sys/socket.h>
20 #include <boost/thread/thread.hpp>
21 #include <boost/thread/mutex.hpp>
22 #include <boost/thread/condition.hpp>
29 #include <yazpp/socket-observer.h>
32 #include "thread_pool_observer.hpp"
35 namespace mp = metaproxy_1;
37 namespace metaproxy_1 {
38 class ThreadPoolSocketObserver::Worker {
40 Worker(ThreadPoolSocketObserver *s) : m_s(s) {};
41 ThreadPoolSocketObserver *m_s;
42 void operator() (void) {
47 class ThreadPoolSocketObserver::Rep : public boost::noncopyable {
48 friend class ThreadPoolSocketObserver;
50 Rep(yazpp_1::ISocketObservable *obs);
53 yazpp_1::ISocketObservable *m_socketObservable;
55 boost::thread_group m_thrds;
56 boost::mutex m_mutex_input_data;
57 boost::condition m_cond_input_data;
58 boost::mutex m_mutex_output_data;
59 std::deque<IThreadPoolMsg *> m_input;
60 std::deque<IThreadPoolMsg *> m_output;
67 using namespace yazpp_1;
70 ThreadPoolSocketObserver::Rep::Rep(ISocketObservable *obs)
71 : m_socketObservable(obs), m_pipe(9123)
75 ThreadPoolSocketObserver::Rep::~Rep()
79 IThreadPoolMsg::~IThreadPoolMsg()
84 ThreadPoolSocketObserver::ThreadPoolSocketObserver(ISocketObservable *obs,
88 obs->addObserver(m_p->m_pipe.read_fd(), this);
89 obs->maskObserver(this, SOCKET_OBSERVE_READ);
91 m_p->m_stop_flag = false;
92 m_p->m_no_threads = no_threads;
94 for (i = 0; i<no_threads; i++)
97 m_p->m_thrds.add_thread(new boost::thread(w));
101 ThreadPoolSocketObserver::~ThreadPoolSocketObserver()
104 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
105 m_p->m_stop_flag = true;
106 m_p->m_cond_input_data.notify_all();
108 m_p->m_thrds.join_all();
110 m_p->m_socketObservable->deleteObserver(this);
113 void ThreadPoolSocketObserver::socketNotify(int event)
115 if (event & SOCKET_OBSERVE_READ)
118 recv(m_p->m_pipe.read_fd(), buf, 1, 0);
121 boost::mutex::scoped_lock output_lock(m_p->m_mutex_output_data);
122 out = m_p->m_output.front();
123 m_p->m_output.pop_front();
130 void ThreadPoolSocketObserver::run(void *p)
134 IThreadPoolMsg *in = 0;
136 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
137 while (!m_p->m_stop_flag && m_p->m_input.size() == 0)
138 m_p->m_cond_input_data.wait(input_lock);
139 if (m_p->m_stop_flag)
142 in = m_p->m_input.front();
143 m_p->m_input.pop_front();
145 IThreadPoolMsg *out = in->handle();
147 boost::mutex::scoped_lock output_lock(m_p->m_mutex_output_data);
148 m_p->m_output.push_back(out);
149 send(m_p->m_pipe.write_fd(), "", 1, 0);
154 void ThreadPoolSocketObserver::put(IThreadPoolMsg *m)
156 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
157 m_p->m_input.push_back(m);
158 m_p->m_cond_input_data.notify_one();
163 * indent-tabs-mode: nil
164 * c-file-style: "stroustrup"
166 * vim: shiftwidth=4 tabstop=8 expandtab