Bump copyright year
[yazpp-moved-to-github.git] / src / yaz-pdu-assoc-thread.cpp
1 /* This file is part of the yazpp toolkit.
2  * Copyright (C) 1998-2010 Index Data and Mike Taylor
3  * See the file LICENSE for details.
4  */
5
6 #ifdef WIN32
7 #define USE_THREADS 1
8 #endif
9
10 #if YAZ_POSIX_THREADS
11 #define USE_THREADS 1
12 #endif
13
14 #if USE_THREADS
15
16 #if HAVE_UNISTD_H
17 #include <unistd.h>
18 #endif
19
20 #ifdef WIN32
21 #include <process.h>
22 #else
23 #include <pthread.h>
24 #endif
25
26
27 #include <errno.h>
28 #include <yaz/log.h>
29 #include <yaz/tcpip.h>
30
31 #include <yazpp/pdu-assoc.h>
32 #include <yazpp/socket-manager.h>
33
34 using namespace yazpp_1;
35
36 class worker {
37 public:
38     SocketManager *m_mgr;
39     PDU_Assoc *m_assoc;
40     void run();
41 };
42
43 PDU_AssocThread::PDU_AssocThread(
44     ISocketObservable *socketObservable)
45     : PDU_Assoc(socketObservable)
46 {
47     
48 }
49
50 void worker::run()
51 {
52     yaz_log (YLOG_LOG, "thread started");
53     while (this->m_mgr->processEvent() > 0)
54         ;
55     yaz_log (YLOG_LOG, "thread finished");
56     delete this->m_mgr;
57     delete this;
58 }
59
60 #ifdef WIN32
61 void __cdecl
62 #else
63 void *
64 #endif 
65 events(void *p)
66 {
67     worker *w = (worker *) p;
68     w->run();
69 #ifdef WIN32
70 #else
71     return 0;
72 #endif
73 }
74
75 void PDU_AssocThread::childNotify(COMSTACK cs)
76 {
77     SocketManager *socket_observable = new SocketManager;
78     PDU_Assoc *new_observable = new PDU_Assoc (socket_observable, cs);
79
80     /// Clone PDU Observer
81     new_observable->m_PDU_Observer =
82         m_PDU_Observer->sessionNotify(new_observable, cs_fileno(cs));
83     
84     if (!new_observable->m_PDU_Observer)
85     {
86         new_observable->shutdown();
87         delete new_observable;
88         delete socket_observable;
89         return;
90     }
91
92     worker *w = new worker;
93     w->m_assoc = new_observable;
94     w->m_mgr = socket_observable;
95
96 #ifdef WIN32
97     long t_id;
98     t_id = _beginthread (events, 0, w);
99     if (t_id == -1)
100     {
101         yaz_log (YLOG_FATAL|YLOG_ERRNO, "_beginthread failed");
102         exit (1);
103     }
104 #else
105     pthread_t tid;
106
107     int id = pthread_create (&tid, 0, events, w);
108     if (id)
109         yaz_log (YLOG_ERRNO|YLOG_FATAL, "pthread_create returned id=%d", id);
110     else
111         pthread_detach (tid);
112 #endif
113 }
114 #endif
115 /*
116  * Local variables:
117  * c-basic-offset: 4
118  * c-file-style: "Stroustrup"
119  * indent-tabs-mode: nil
120  * End:
121  * vim: shiftwidth=4 tabstop=8 expandtab
122  */
123