2 /* $Id: thread_pool_observer.cpp,v 1.13 2005-11-07 22:46:42 adam Exp $
3 Copyright (c) 2005, 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 <yaz++/socket-observer.h>
32 #include "thread_pool_observer.hpp"
36 class ThreadPoolSocketObserver::Worker {
38 Worker(ThreadPoolSocketObserver *s) : m_s(s) {};
39 ThreadPoolSocketObserver *m_s;
40 void operator() (void) {
45 class ThreadPoolSocketObserver::Rep : public boost::noncopyable {
46 friend class ThreadPoolSocketObserver;
48 Rep(yazpp_1::ISocketObservable *obs);
51 yazpp_1::ISocketObservable *m_socketObservable;
53 boost::thread_group m_thrds;
54 boost::mutex m_mutex_input_data;
55 boost::condition m_cond_input_data;
56 boost::mutex m_mutex_output_data;
57 std::deque<IThreadPoolMsg *> m_input;
58 std::deque<IThreadPoolMsg *> m_output;
65 using namespace yazpp_1;
68 ThreadPoolSocketObserver::Rep::Rep(ISocketObservable *obs)
69 : m_socketObservable(obs), m_pipe(9123)
73 ThreadPoolSocketObserver::Rep::~Rep()
77 IThreadPoolMsg::~IThreadPoolMsg()
82 ThreadPoolSocketObserver::ThreadPoolSocketObserver(ISocketObservable *obs,
86 obs->addObserver(m_p->m_pipe.read_fd(), this);
87 obs->maskObserver(this, SOCKET_OBSERVE_READ);
89 m_p->m_stop_flag = false;
90 m_p->m_no_threads = no_threads;
92 for (i = 0; i<no_threads; i++)
95 m_p->m_thrds.add_thread(new boost::thread(w));
99 ThreadPoolSocketObserver::~ThreadPoolSocketObserver()
102 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
103 m_p->m_stop_flag = true;
104 m_p->m_cond_input_data.notify_all();
106 m_p->m_thrds.join_all();
108 m_p->m_socketObservable->deleteObserver(this);
111 void ThreadPoolSocketObserver::socketNotify(int event)
113 if (event & SOCKET_OBSERVE_READ)
116 recv(m_p->m_pipe.read_fd(), buf, 1, 0);
119 boost::mutex::scoped_lock output_lock(m_p->m_mutex_output_data);
120 out = m_p->m_output.front();
121 m_p->m_output.pop_front();
128 void ThreadPoolSocketObserver::run(void *p)
132 IThreadPoolMsg *in = 0;
134 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
135 while (!m_p->m_stop_flag && m_p->m_input.size() == 0)
136 m_p->m_cond_input_data.wait(input_lock);
137 if (m_p->m_stop_flag)
140 in = m_p->m_input.front();
141 m_p->m_input.pop_front();
143 IThreadPoolMsg *out = in->handle();
145 boost::mutex::scoped_lock output_lock(m_p->m_mutex_output_data);
146 m_p->m_output.push_back(out);
147 send(m_p->m_pipe.write_fd(), "", 1, 0);
152 void ThreadPoolSocketObserver::put(IThreadPoolMsg *m)
154 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
155 m_p->m_input.push_back(m);
156 m_p->m_cond_input_data.notify_one();
161 * indent-tabs-mode: nil
162 * c-file-style: "stroustrup"
164 * vim: shiftwidth=4 tabstop=8 expandtab