debian: added giffgaff chatscripts
[barry.git] / src / threadwrap.cc
blob666197a80752d929382bbcecf3a72fd10f073296
1 ///
2 /// \file threadwrap.cc
3 /// RAII Wrapper for a single thread.
4 ///
6 /*
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.
22 #include "i18n.h"
23 #include "threadwrap.h"
24 #include "error.h"
25 #include <sys/socket.h>
27 namespace Barry {
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)
37 : callback(0)
38 , stopflag(false)
39 , userdata(userdata)
43 Thread::Thread(int socket,
44 void *(*callback)(Barry::Thread::CallbackData *data),
45 void *userdata)
46 : m_socket(socket)
48 m_data = new CallbackData(userdata);
49 m_data->callback = callback;
51 int ret = pthread_create(&thread, NULL, callback_wrapper, m_data);
52 if( ret ) {
53 delete m_data;
54 throw Barry::ErrnoError(_("Thread: pthread_create failed."), ret);
58 Thread::~Thread()
60 if( pthread_join(thread, NULL) == 0 ) {
61 // successful join, thread is dead, free to free
62 delete m_data;
64 else {
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);
81 } // namespace Barry