29 #include <boost/thread/thread.hpp>
30 #include <boost/thread/mutex.hpp>
31 #include <boost/thread/condition.hpp>
39 #include <yazpp/socket-observer.h>
45 namespace metaproxy_1 {
58 Rep(yazpp_1::ISocketObservable *obs);
79 using namespace yazpp_1;
80 using namespace metaproxy_1;
82 ThreadPoolSocketObserver::Rep::Rep(yazpp_1::ISocketObservable *obs)
83 : m_socketObservable(obs), m_pipe(9123)
97 yazpp_1::ISocketObservable *obs,
int no_threads)
100 obs->addObserver(
m_p->m_pipe.read_fd(),
this);
101 obs->maskObserver(
this, SOCKET_OBSERVE_READ);
103 m_p->m_stop_flag =
false;
104 m_p->m_no_threads = no_threads;
105 m_p->m_no_threads_waiting = 0;
107 for (i = 0; i<no_threads; i++)
110 m_p->m_thrds.add_thread(
new boost::thread(w));
117 boost::mutex::scoped_lock input_lock(
m_p->m_mutex_input_data);
118 m_p->m_stop_flag =
true;
119 m_p->m_cond_input_data.notify_all();
121 m_p->m_thrds.join_all();
123 m_p->m_socketObservable->deleteObserver(
this);
128 if (event & SOCKET_OBSERVE_READ)
132 recv(
m_p->m_pipe.read_fd(), buf, 1, 0);
134 ssize_t r = read(
m_p->m_pipe.read_fd(), buf, 1);
137 if (r == (ssize_t) (-1))
138 yaz_log(YLOG_WARN|YLOG_ERRNO,
139 "ThreadPoolSocketObserver::socketNotify. read fail");
142 "ThreadPoolSocketObserver::socketNotify. read returned 0");
147 boost::mutex::scoped_lock output_lock(
m_p->m_mutex_output_data);
148 out =
m_p->m_output.front();
149 m_p->m_output.pop_front();
155 std::ostringstream os;
157 boost::mutex::scoped_lock input_lock(
m_p->m_mutex_input_data);
158 os <<
"tbusy/total " <<
159 m_p->m_no_threads -
m_p->m_no_threads_waiting <<
160 "/" <<
m_p->m_no_threads
161 <<
" queue in/out " <<
m_p->m_input.size() <<
"/"
162 <<
m_p->m_output.size();
164 out->
result(os.str().c_str());
171 tbusy =
m_p->m_no_threads -
m_p->m_no_threads_waiting;
172 total =
m_p->m_no_threads;
181 boost::mutex::scoped_lock input_lock(
m_p->m_mutex_input_data);
182 m_p->m_no_threads_waiting++;
183 while (!
m_p->m_stop_flag &&
m_p->m_input.size() == 0)
184 m_p->m_cond_input_data.wait(input_lock);
185 m_p->m_no_threads_waiting--;
186 if (
m_p->m_stop_flag)
189 in =
m_p->m_input.front();
190 m_p->m_input.pop_front();
191 m_p->m_cond_input_full.notify_all();
195 boost::mutex::scoped_lock output_lock(
m_p->m_mutex_output_data);
196 m_p->m_output.push_back(out);
198 send(
m_p->m_pipe.write_fd(),
"", 1, 0);
200 ssize_t r = write(
m_p->m_pipe.write_fd(),
"", 1);
203 if (r == (ssize_t) (-1))
204 yaz_log(YLOG_WARN|YLOG_ERRNO,
205 "ThreadPoolSocketObserver::run. write fail");
208 "ThreadPoolSocketObserver::run. write returned 0");
217 boost::mutex::scoped_lock input_lock(
m_p->m_mutex_input_data);
219 std::deque<IThreadPoolMsg *>::iterator it =
m_p->m_input.begin();
220 while (it !=
m_p->m_input.end())
222 if ((*it)->cleanup(info))
223 it =
m_p->m_input.erase(it);
231 boost::mutex::scoped_lock input_lock(
m_p->m_mutex_input_data);
234 m_p->m_cond_input_full.wait(input_lock);
235 m_p->m_input.push_back(m);
236 m_p->m_cond_input_data.notify_one();