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