Implemented new class Msg_Thread which allows for threaded facilities
[yazproxy-moved-to-github.git] / src / tstthreads.cpp
1 /* $Id: tstthreads.cpp,v 1.3 2005-05-30 20:08:58 adam Exp $
2    Copyright (c) 1998-2005, Index Data.
3
4 This file is part of the yaz-proxy.
5
6 YAZ proxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 YAZ proxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with YAZ proxy; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 #include <stdlib.h>
23 #include <ctype.h>
24
25 #include <yaz++/pdu-assoc.h>
26 #include <yaz++/socket-manager.h>
27 #include <yaz/log.h>
28 #include "msg-thread.h"
29
30 class My_Msg : public IMsg_Thread {
31 public:
32     IMsg_Thread *handle();
33     void result();
34     int m_val;
35 };
36
37 IMsg_Thread *My_Msg::handle()
38 {
39     My_Msg *res = new My_Msg;
40     int sl = rand() % 5;
41
42     res->m_val = m_val;
43     printf("My_Msg::handle val=%d sleep=%d\n", m_val, sl);
44     sleep(sl);
45     return res;
46 }
47
48 void My_Msg::result()
49 {
50     printf("My_Msg::result val=%d\n", m_val);
51 }
52
53 class My_Timer_Thread : public IYazSocketObserver {
54 private:
55     IYazSocketObservable *m_obs;
56     int m_fd[2];
57     Msg_Thread *m_t;
58 public:
59     My_Timer_Thread(IYazSocketObservable *obs, Msg_Thread *t);
60     void socketNotify(int event);
61 };
62
63 My_Timer_Thread::My_Timer_Thread(IYazSocketObservable *obs,
64                                  Msg_Thread *t) : m_obs(obs) 
65 {
66     pipe(m_fd);
67     m_t = t;
68     obs->addObserver(m_fd[0], this);
69     obs->maskObserver(this, YAZ_SOCKET_OBSERVE_READ);
70     obs->timeoutObserver(this, 2);
71 }
72
73 void My_Timer_Thread::socketNotify(int event)
74 {
75     static int seq = 1;
76     printf("Add %d\n", seq);
77     My_Msg *m = new My_Msg;
78     m->m_val = seq++;
79     m_t->put(m);
80 }
81
82 int main(int argc, char **argv)
83 {
84     Yaz_SocketManager mySocketManager;
85
86     Msg_Thread m(&mySocketManager);
87     My_Timer_Thread t(&mySocketManager, &m) ;
88     int i = 0;
89     while (++i < 5 && mySocketManager.processEvent() > 0)
90         ;
91     return 0;
92 }