Handle present out of range better in sample server.
[yazpp-moved-to-github.git] / src / yaz-pdu-assoc-thread.cpp
1 /*
2  * Copyright (c) 1998-2004, Index Data.
3  * See the file LICENSE for details.
4  * 
5  * $Id: yaz-pdu-assoc-thread.cpp,v 1.9 2005-01-14 10:13:50 adam Exp $
6  */
7
8 #ifdef WIN32
9 #define USE_THREADS 1
10 #endif
11
12 #if YAZ_POSIX_THREADS
13 #define USE_THREADS 1
14 #endif
15
16 #if USE_THREADS
17
18 #if HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21
22 #ifdef WIN32
23 #include <process.h>
24 #else
25 #include <pthread.h>
26 #endif
27
28
29 #include <errno.h>
30 #include <yaz/log.h>
31 #include <yaz/tcpip.h>
32
33 #include <yaz++/pdu-assoc.h>
34 #include <yaz++/socket-manager.h>
35
36 Yaz_PDU_AssocThread::Yaz_PDU_AssocThread(
37     IYazSocketObservable *socketObservable)
38     : Yaz_PDU_Assoc(socketObservable)
39 {
40     
41 }
42
43 #ifdef WIN32
44 void __cdecl
45 #else
46 void *
47 #endif 
48 events(void *p)
49 {
50     Yaz_SocketManager *s = (Yaz_SocketManager *) p;
51     
52     yaz_log (YLOG_LOG, "thread started");
53     while (s->processEvent() > 0)
54         ;
55     yaz_log (YLOG_LOG, "thread finished");
56 #ifdef WIN32
57 #else
58     return 0;
59 #endif
60 }
61
62 void Yaz_PDU_AssocThread::childNotify(COMSTACK cs)
63 {
64     Yaz_SocketManager *socket_observable = new Yaz_SocketManager;
65     Yaz_PDU_Assoc *new_observable = new Yaz_PDU_Assoc (socket_observable, cs);
66
67     new_observable->m_next = m_children;
68     m_children = new_observable;
69     new_observable->m_parent = this;
70
71     /// Clone PDU Observer
72     new_observable->m_PDU_Observer =
73         m_PDU_Observer->sessionNotify(new_observable, cs_fileno(cs));
74 #ifdef WIN32
75     long t_id;
76     t_id = _beginthread (events, 0, socket_observable);
77     if (t_id == -1)
78     {
79         yaz_log (YLOG_FATAL|YLOG_ERRNO, "_beginthread failed");
80         exit (1);
81     }
82 #else
83     pthread_t tid;
84
85     int id = pthread_create (&tid, 0, events, socket_observable);
86     if (id)
87         yaz_log (YLOG_ERRNO|YLOG_FATAL, "pthread_create returned id=%d", id);
88     else
89         pthread_detach (tid);
90 #endif
91 }
92 #endif