2 /// \file threadwrap.cc
3 /// RAII Wrapper for a single thread.
7 Copyright (C) 2009, Nicolas VIVIEN
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
23 #include "threadwrap.h"
25 #include <sys/socket.h>
29 void *callback_wrapper(void *data
)
31 Barry::Thread::CallbackData
*cbdata
= (Barry::Thread::CallbackData
*) data
;
33 return (*cbdata
->callback
)(cbdata
);
36 Thread::CallbackData::CallbackData(void *userdata
)
43 Thread::Thread(int socket
,
44 void *(*callback
)(Barry::Thread::CallbackData
*data
),
48 m_data
= new CallbackData(userdata
);
49 m_data
->callback
= callback
;
51 int ret
= pthread_create(&thread
, NULL
, callback_wrapper
, m_data
);
54 throw Barry::ErrnoError(_("Thread: pthread_create failed."), ret
);
60 if( pthread_join(thread
, NULL
) == 0 ) {
61 // successful join, thread is dead, free to free
65 // thread is in la-la land, must leak m_data here for safety
69 void Thread::StopFlag()
71 // http://stackoverflow.com/questions/2486335/wake-up-thread-blocked-on-accept-call
73 // set flag first, before waking thread
74 m_data
->stopflag
= true;
76 // shutdown the socket, but leave the fd valid, thereby waking up
77 // the thread if it is blocked on accept()
78 shutdown(m_socket
, SHUT_RDWR
);