Same header and footer for all files. Header includes copyright +
[metaproxy-moved-to-github.git] / src / thread_pool_observer.cpp
1 /* $Id: thread_pool_observer.cpp,v 1.7 2005-10-15 14:09:09 adam Exp $
2    Copyright (c) 2005, Index Data.
3
4 %LICENSE%
5  */
6 #include <unistd.h>
7 #include <ctype.h>
8 #include <stdio.h>
9
10 #include <yaz++/socket-observer.h>
11 #include <yaz/log.h>
12
13 #include "config.hpp"
14 #include "thread_pool_observer.hpp"
15
16 using namespace yazpp_1;
17 using namespace yp2;
18
19 IThreadPoolMsg::~IThreadPoolMsg()
20 {
21
22 }
23
24 ThreadPoolSocketObserver::ThreadPoolSocketObserver(ISocketObservable *obs, int no_threads)
25     : m_SocketObservable(obs)
26 {
27     pipe(m_fd);
28     obs->addObserver(m_fd[0], this);
29     obs->maskObserver(this, SOCKET_OBSERVE_READ);
30
31     m_stop_flag = false;
32     m_no_threads = no_threads;
33     int i;
34     for (i = 0; i<no_threads; i++)
35     {
36         Worker w(this);
37         m_thrds.add_thread(new boost::thread(w));
38     }
39 }
40
41 ThreadPoolSocketObserver::~ThreadPoolSocketObserver()
42 {
43     {
44         boost::mutex::scoped_lock input_lock(m_mutex_input_data);
45         m_stop_flag = true;
46         m_cond_input_data.notify_all();
47     }
48     m_thrds.join_all();
49
50     m_SocketObservable->deleteObserver(this);
51
52     close(m_fd[0]);
53     close(m_fd[1]);
54 }
55
56 void ThreadPoolSocketObserver::socketNotify(int event)
57 {
58     if (event & SOCKET_OBSERVE_READ)
59     {
60         char buf[2];
61         read(m_fd[0], buf, 1);
62         IThreadPoolMsg *out;
63         {
64             boost::mutex::scoped_lock output_lock(m_mutex_output_data);
65             out = m_output.front();
66             m_output.pop_front();
67         }
68         if (out)
69             out->result();
70     }
71 }
72
73 void ThreadPoolSocketObserver::run(void *p)
74 {
75     while(1)
76     {
77         IThreadPoolMsg *in = 0;
78         {
79             boost::mutex::scoped_lock input_lock(m_mutex_input_data);
80             while (!m_stop_flag && m_input.size() == 0)
81                 m_cond_input_data.wait(input_lock);
82             if (m_stop_flag)
83                 break;
84             
85             in = m_input.front();
86             m_input.pop_front();
87         }
88         IThreadPoolMsg *out = in->handle();
89         {
90             boost::mutex::scoped_lock output_lock(m_mutex_output_data);
91             m_output.push_back(out);
92             write(m_fd[1], "", 1);
93         }
94     }
95 }
96
97 void ThreadPoolSocketObserver::put(IThreadPoolMsg *m)
98 {
99     boost::mutex::scoped_lock input_lock(m_mutex_input_data);
100     m_input.push_back(m);
101     m_cond_input_data.notify_one();
102 }
103 /*
104  * Local variables:
105  * c-basic-offset: 4
106  * indent-tabs-mode: nil
107  * c-file-style: "stroustrup"
108  * End:
109  * vim: shiftwidth=4 tabstop=8 expandtab
110  */
111