2 /* $Id: thread_pool_observer.cpp,v 1.11 2005-11-07 21:57:10 adam Exp $
3 Copyright (c) 2005, Index Data.
16 #include <boost/thread/thread.hpp>
17 #include <boost/thread/mutex.hpp>
18 #include <boost/thread/condition.hpp>
25 #include <yaz++/socket-observer.h>
28 #include "thread_pool_observer.hpp"
32 class ThreadPoolSocketObserver::Worker {
34 Worker(ThreadPoolSocketObserver *s) : m_s(s) {};
35 ThreadPoolSocketObserver *m_s;
36 void operator() (void) {
41 class ThreadPoolSocketObserver::Rep : public boost::noncopyable {
42 friend class ThreadPoolSocketObserver;
44 Rep(yazpp_1::ISocketObservable *obs);
47 yazpp_1::ISocketObservable *m_socketObservable;
49 boost::thread_group m_thrds;
50 boost::mutex m_mutex_input_data;
51 boost::condition m_cond_input_data;
52 boost::mutex m_mutex_output_data;
53 std::deque<IThreadPoolMsg *> m_input;
54 std::deque<IThreadPoolMsg *> m_output;
61 using namespace yazpp_1;
64 ThreadPoolSocketObserver::Rep::Rep(ISocketObservable *obs)
65 : m_socketObservable(obs), m_pipe(9123)
69 ThreadPoolSocketObserver::Rep::~Rep()
73 IThreadPoolMsg::~IThreadPoolMsg()
78 ThreadPoolSocketObserver::ThreadPoolSocketObserver(ISocketObservable *obs,
82 obs->addObserver(m_p->m_pipe.read_fd(), this);
83 obs->maskObserver(this, SOCKET_OBSERVE_READ);
85 m_p->m_stop_flag = false;
86 m_p->m_no_threads = no_threads;
88 for (i = 0; i<no_threads; i++)
91 m_p->m_thrds.add_thread(new boost::thread(w));
95 ThreadPoolSocketObserver::~ThreadPoolSocketObserver()
98 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
99 m_p->m_stop_flag = true;
100 m_p->m_cond_input_data.notify_all();
102 m_p->m_thrds.join_all();
104 m_p->m_socketObservable->deleteObserver(this);
107 void ThreadPoolSocketObserver::socketNotify(int event)
109 if (event & SOCKET_OBSERVE_READ)
112 read(m_p->m_pipe.read_fd(), buf, 1);
115 boost::mutex::scoped_lock output_lock(m_p->m_mutex_output_data);
116 out = m_p->m_output.front();
117 m_p->m_output.pop_front();
124 void ThreadPoolSocketObserver::run(void *p)
128 IThreadPoolMsg *in = 0;
130 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
131 while (!m_p->m_stop_flag && m_p->m_input.size() == 0)
132 m_p->m_cond_input_data.wait(input_lock);
133 if (m_p->m_stop_flag)
136 in = m_p->m_input.front();
137 m_p->m_input.pop_front();
139 IThreadPoolMsg *out = in->handle();
141 boost::mutex::scoped_lock output_lock(m_p->m_mutex_output_data);
142 m_p->m_output.push_back(out);
143 write(m_p->m_pipe.write_fd(), "", 1);
148 void ThreadPoolSocketObserver::put(IThreadPoolMsg *m)
150 boost::mutex::scoped_lock input_lock(m_p->m_mutex_input_data);
151 m_p->m_input.push_back(m);
152 m_p->m_cond_input_data.notify_one();
157 * indent-tabs-mode: nil
158 * c-file-style: "stroustrup"
160 * vim: shiftwidth=4 tabstop=8 expandtab