Interruption handling with non-static member function - c++

I am trying to do interruption handling with a member function from a class.
The code is
signal(SIGABRT, socketServer.signalHandler);
where the definition of signalHandler is
public:
void SocketServer::signalHandler(int sig)
{
logger.info("Receive SIG"+to_string(sig)+" Stopping server now...");
stop();
}
When I compile the code, I got an error says
main.cpp:32:32: error: reference to non-static member function must be called
signal(SIGABRT, socketServer.signalHandler);
I am trying to capture SIGABRT using this signalHandler function and to clean up and stop the socketServer instance. I guess I can use global variable and a global function to do the job, but any thoughts about doing this with a member function?

No, you can not do this.
The reason is that all member functions have an "implied/hidden" this pointer argument. If we "flattened" out your handler definition to produce the C equivalent, it would look like:
void SocketServer::signalHandler(SocketServer *this,int sig);
The signal function [in C] knows nothing of this [pun intended]. If it compiled, the handler would be called with sig going into the this argument and not the sig argument.
So, you really must do:
SocketServer my_global_server;
void
my_handler(int sig)
{
my_global_server.signalHandler(sig);
}
int
main(void)
{
signal(SIGABRT,my_handler);
return 0;
}
Actually, the above is quite dangerous because my_global_server may be in an indeterminate state when the signal handler is called, causing UB. Also, when in a signal handler, there are a limited number of things you are permitted to do. For example, no heap manipulations are permitted.
Here is a better way to implement this:
volatile int signal_flag;
SocketServer my_global_server;
void
my_handler(int sig)
{
signal_flag = sig;
}
int
main(void)
{
signal(SIGABRT,my_handler);
while (! signal_flag) {
...
}
my_global_server.signalHandler(signal_flag);
return 0;
}

Related

Class with no blocking methodes with multithreading

I am programming a class which should use multithreading features.
The goal is that I don't have any blocking methods from the outside although I use libraries in the class that have blocking functions.
I want to run them in their own threads.
Unfortunately I get a memory fault (core dumped) error.
What would be the best practice in c++11 to implement something like this and why do I get the error,how can I specify the memory for the function I want to call in the thread best in advance?
My Class
..
class foo {
void startUp();
foo();
~foo();
std::thread foo_worker;
int retValue;
};
void foo::startUp() {
int retValue = 0;
std::thread t([this] () {
retValue = blocking_lib_func();
});
foo_worker = std::move(t);
}
foo::~foo() {
....
foo_worker.join();
}
My Main
int main()
foo test();
test.statUp()
}
The lambda associated with your thread is capturing a reference to local stack variable. When startUp returns, the thread will continue on, but the address of retValue is now off limits, including to the thread. The thread will create undefined behavior by trying to assign something to that reference to retValue. That is very likely the source of the crash that you describe. Or worse, stack corruption on the main thread corrupting your program in other ways.
The solution is simple. First, make retValue a member variable of your class. And while we are at it, no reason for foo_worker to be a pointer.
class foo {
public:
void startUp();
foo();
~foo();
private:
std::thread foo_worker;
int retValue;
};
Then your startUp code can be this. We can use std::move to move the thread from the local t thread variable to the member variable of the class instance.
void foo::startUp() {
std::thread t([this] () {
retValue = blocking_lib_func(); // assign to the member variable of foo
});
foo_worker = std::move(t);
}
Then your destructor can invoke join as follows:
foo::~foo() {
....
foo_worker.join();
}
And as other in the comments have pointed out, volatile isn't useful. It's mostly deprecated as a keyword when proper thread and locking semantics are used.

How to "interrupt" a function call?

I am doing a kind of shell: depending of the user's entry, I must call some function. I cannot modify the content of those called functions since my program is only a client and has no visibility of them.
But I want the possibility for the user to kill the call using CTRL+C. Here is the minimal code:
#include <csignal>
#include <iostream>
#include <unistd.h>
void do_thing(void)
{
std::cout << "entering in do_thing()\n";
while(42)
::sleep(1);
}
extern "C" {
void signal_handler(int);
}
class Shell
{
friend void signal_handler(int);
public:
static Shell & Instance(void)
{
static Shell instance;
return instance;
}
int run(void)
{
std::string buff;
while ((std::cin >> buff))
{
if (buff == "foo")
do_thing(); // this must be terminable
else
std::cout << "(nothing)\n";
}
return 0;
}
private:
Shell(void)
{
::signal(SIGINT, signal_handler);
}
void signal(int sig)
{
if (sig == SIGINT)
;// must terminal the function call
}
};
extern "C" {
void signal_handler(int sig)
{
Shell::Instance().signal(sig);
}
}
int main(void)
{
return Shell::Instance().run();
}
I considered three possibilities:
I tried to create a thread class derived from std::thread, with a kill() method that throws an exception. The function call is in a try-catch block. It works, but this is a bad solution since the destructor cannot be called, and the resource is never freed.
I considered using fork, but I think it is an overkill to just get the possibility of interrupt a function call.
I tried to throw an exception from the signal handler, but I saw that this is a bad idea since this is very compiler/OS dependent code.
How could you do the thing? What is the better solution?
Note: I deleted the old post because it was close requested, and took into consideration the C/C++ tags.
Essentially, no, there is no standard why to interrupt a thread in C++. Threads run co-operatively and as such, they need to "give up" control.
If the code for do_thing were modifiable, then you can create a flag (atomic) to signal that the thread should give up and exit. This can be periodically checked by the thread and complete as required.
Given the code for do_thing is not modifiable, there is a small window of opportunity that can be used to "kill" or "cancel" the thread (albeit it won't be "standard" and support will be limited to targeted platforms).
std::thread offers a function to retrieve a native_handle() that is implementation defined. Once obtained (and converted), it can be used to kill or cancel the thread.
If pthreads are being used, see pthread_kill (or pthread_cancel if supported by the target thread).
On windows, see the TerminateThread function.
Be warned; aside from the platform specific code required, the thread terminations generally leave the objects on that thread in "limbo" and with them, the resources they control.

Error : An exception (first chance) at 0x76f6f9d2 in Boost_Mutex.exe: 0xC0000008: An invalid handle was specified

I write a program to test multithreading. In main function a thread t is created. In function D, which is in thread t, two threads tt and ttt will be created. The function Process runs in thread ttt . In Process a member function doAnotherThing of class Dat will be called. In thread tt a member function doOneThing will be called.
When I debug this program, an error occured: An exception (first chance) at 0x76f6f9d2 in Boost_Mutex.exe: 0xC0000008: An invalid handle was specified.
Sometimes this error occured instead of the error above :
Run-Time Check Failure #2 - Stack around the variable 'oDat' was corrupted.
Can anyone help me to solve this Problem and modify the codes?
These are my codes:
"Dat.h"
#pragma once
#ifndef DAT_H
#define DAT_H
#include <boost\thread\thread.hpp>
using namespace std;
class Dat
{
public:
Dat();
~Dat();
void doOneThing();
void doAnotherThing ();
private:
boost::mutex omutex;
int x;
};
#endif // DAT_H
"Dat.cpp"
#include "Dat.h"
Dat::Dat()
{
}
Dat::~Dat()
{
}
void Dat::doOneThing()
{
x = 1;
}
void Dat::doAnotherThing()
{
omutex.lock();
x = 2;
omutex.unlock();
}
"main.cpp"
#include "Dat.h"
#include <boost\function.hpp>
struct Parameter // the Parameters of function Process and D
{
Dat* pDat;
};
void Process(void*pParam)
{
// init the parameter
parameter* pUserParams = (parameter*)pParam;
pUserParams->pDat->doAnotherThing();
}
void D(void* pParam)
{
// init the parameter
parameter* pUserParams = (parameter*)pParam;
boost::function<void()> f;
boost::thread ttt(Process, (void*)&pParam);
f = boost::bind(&Dat::doOneThing, pUserParams->pDat);
// the capture thread will be started
boost::thread tt(f);
ttt.join();
tt.join();
}
void main()
{
Dat oDat;
parameter pPara ;
pPara.pDat = &oDat;
boost::thread t(D,(void*)&pPara);
t.join();
}
If you have suggestions to this statement of my quesion, pleas tell me and i will modify it. Thank you
The main problem here is this line:
boost::thread ttt(Process, (void*)&pParam);
You take the address of pParam (which is already a pointer), yielding a void**, and then cast it back to a void*. The C++ threading interface is type-safe. The fact that you have to cast is a strong indicator that you're doing something wrong. (Also, your usage of void* all over the place. This is needed for C threading interfaces, but not for C++.)
Anyway, in Process you then take the parameter, which points to pParam, and pretend that it points to your pPara object. (Why is that prefixed p anyway? It's not a pointer!) Then you reach into it to the pDat pointer, which is of course nonsense, because there's no Parameter struct there in the first place. So the pointer you get isn't valid, and doesn't point to a valid Dat struct, which means that the mutex in there isn't valid either, which means its internal thread handle isn't valid, so you finally get the crash you need when you try to lock the mutex.
Here's how you fix your code: get rid of all void pointer and get rid of all casts. Also, which not strictly necessary, you should also get rid of the variable prefixes. A redundant naming convention is bad enough, but an incorrectly applied redundant naming convention is a disaster.
You have one more error: you don't protect all your accesses to x with the mutex, just one. This is useless. You've still got the race condition. You have to protect all accesses to a shared variable. Also, you should use a lock_guard RAII object instead of manually calling lock and unlock, so that you can never forget to unlock.

pthread_key_create destructor not getting called

As per pthread_key_create man page we can associate a destructor to be called at thread shut down. My problem is that the destructor function I have registered is not being called. Gist of my code is as follows.
static pthread_key_t key;
static pthread_once_t tls_init_flag = PTHREAD_ONCE_INIT;
void destructor(void *t) {
// thread local data structure clean up code here, which is not getting called
}
void create_key() {
pthread_key_create(&key, destructor);
}
// This will be called from every thread
void set_thread_specific() {
ts = new ts_stack; // Thread local data structure
pthread_once(&tls_init_flag, create_key);
pthread_setspecific(key, ts);
}
Any idea what might prevent this destructor being called? I am also using atexit() at moment to do some cleanup in the main thread. Is there any chance that is interfering with destructor function being called? I tried removing that as well. Still didn't work though. Also I am not clear if I should handle the main thread as a separate case with atexit. (It's a must to use atexit by the way, since I need to do some application specific cleanup at application exit)
This is by design.
The main thread exits (by returning or calling exit()), and that doesn't use pthread_exit(). POSIX documents pthread_exit calling the thread-specific destructors.
You could add pthread_exit() at the end of main. Alternatively, you can use atexit to do your destruction. In that case, it would be clean to set the thread-specific value to NULL so in case the pthread_exit was invoked, the destruction wouldn't happen twice for that key.
UPDATE Actually, I've solved my immediate worries by simply adding this to my global unit test setup function:
::atexit([] { ::pthread_exit(0); });
So, in context of my global fixture class MyConfig:
struct MyConfig {
MyConfig() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::atexit([] { ::pthread_exit(0); });
}
~MyConfig() { google::protobuf::ShutdownProtobufLibrary(); }
};
Some of the references used:
http://www.resolvinghere.com/sof/6357154.shtml
https://sourceware.org/ml/pthreads-win32/2008/msg00007.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_key_create.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_exit.html
PS. Of course c++11 introduced <thread> so you have better and more portable primitves to work with.
It's already in sehe's answer, just to present the key points in a compact way:
pthread_key_create() destructor calls are triggered by a call to pthread_exit().
If the start routine of a thread returns, the behaviour is as if pthread_exit() was called (i. e., destructor calls are triggered).
However, if main() returns, the behaviour is as if exit() was called — no destructor calls are triggered.
This is explained in http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_create.html. See also C++17 6.6.1p5 or C11 5.1.2.2.3p1.
I wrote a quick test and the only thing I changed was moving the create_key call of yours outside of the set_thread_specific.
That is, I called it within the main thread.
I then saw my destroy get called when the thread routine exited.
I call destructor() manually at the end of main():
void * ThreadData = NULL;
if ((ThreadData = pthread_getspecific(key)) != NULL)
destructor(ThreadData);
Of course key should be properly initialized earlier in main() code.
PS. Calling Pthread_Exit() at the end to main() seems to hang entire application...
Your initial thought of handling the main thread as a separate case with atexit worked best for me.
Be ware that pthread_exit(0) overwrites the exit value of the process. For example, the following program will exit with status of zero even though main() returns with number three:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
class ts_stack {
public:
ts_stack () {
printf ("init\n");
}
~ts_stack () {
printf ("done\n");
}
};
static void cleanup (void);
static pthread_key_t key;
static pthread_once_t tls_init_flag = PTHREAD_ONCE_INIT;
void destructor(void *t) {
// thread local data structure clean up code here, which is not getting called
delete (ts_stack*) t;
}
void create_key() {
pthread_key_create(&key, destructor);
atexit(cleanup);
}
// This will be called from every thread
void set_thread_specific() {
ts_stack *ts = new ts_stack (); // Thread local data structure
pthread_once(&tls_init_flag, create_key);
pthread_setspecific(key, ts);
}
static void cleanup (void) {
pthread_exit(0); // <-- Calls destructor but sets exit status to zero as a side effect!
}
int main (int argc, char *argv[]) {
set_thread_specific();
return 3; // Attempt to exit with status of 3
}
I had similar issue as yours: pthread_setspecific sets a key, but the destructor never gets called. To fix it we simply switched to thread_local in C++. You could also do something like if that change is too complicated:
For example, assume you have some class ThreadData that you want some action to be done on when the thread finishes execution. You define the destructor something on these lines:
void destroy_my_data(ThreadlData* t) {
delete t;
}
When your thread starts, you allocate memory for ThreadData* instance and assign a destructor to it like this:
ThreadData* my_data = new ThreadData;
thread_local ThreadLocalDestructor<ThreadData> tld;
tld.SetDestructorData(my_data, destroy_my_data);
pthread_setspecific(key, my_data)
Notice that ThreadLocalDestructor is defined as thread_local. We rely on C++11 mechanism that when the thread exits, the destructor of ThreadLocalDestructor will be automatically called, and ~ThreadLocalDestructor is implemented to call function destroy_my_data.
Here is the implementation of ThreadLocalDestructor:
template <typename T>
class ThreadLocalDestructor
{
public:
ThreadLocalDestructor() : m_destr_func(nullptr), m_destr_data(nullptr)
{
}
~ThreadLocalDestructor()
{
if (m_destr_func) {
m_destr_func(m_destr_data);
}
}
void SetDestructorData(void (*destr_func)(T*), T* destr_data)
{
m_destr_data = destr_data;
m_destr_func = destr_func;
}
private:
void (*m_destr_func)(T*);
T* m_destr_data;
};

Can the signal system call be used with C++ static members of the class?

Is the following supported across *nix platforms?
#include <cstdio>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
class SignalProcessor
{
public:
static void OnMySignal(int sig_num)
{
printf("Caught %d signal\n", sig_num);
fflush(stdout);
return;
}
};
using namespace std;
int main()
{
signal(SIGINT,SingalProcessor::OnMySignal);
printf("Ouch\n");
pause();
return 0;
}
Technically no you can't.
You just happen to be getting lucky that your compiler is using the same calling convention that it uses for 'C' functions. As the C++ ABI is not defined the next version of the compiler is free to use a completely different calling convention and this will mess with your code with no warning from the compiler.
See: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2
See the note at the end of this section
Note: static member functions do not require an actual object to be invoked,
so pointers-to-static-member-functions are usually type-compatible with regular
pointers-to-functions. However, although it probably works on most compilers,
it actually would have to be an extern "C" non-member function to be correct,
since "C linkage" doesn't only cover things like name mangling, but also
calling conventions, which might be different between C and C++.
Edit:
To answer the comment by Sasha:
Using threading as an example:
#include <iostream>
class Thread
{ public: virtual void run() = 0; };
extern "C" void* startThrerad(void* data)
{
Thread* thread = reinterpret_cast<Thread*>(data);
try
{
thread->run();
}
catch(...)
{ /* Log if required. Don't let thread exit with exception. */ }
return NULL;
}
class MyJob: public Thread
{
public: virtual void run() {std::cout << "HI\n";}
};
int main()
{
MyJob job; // MyJob inherits from Thread
pthread_t th;
// In most situation you do not need to dynamic cast.
// But if you use multiple inheritance then things may get
// interesting, as such best to always use it.
pthread_create(&th,NULL,startThrerad,dynamic_cast<Thread*>(&job));
void* result;
pthread_join(th,&result);
}
That should work just fine. In fact, you could expand that function to call specific instances of that class dependent on the signal caught. For example, if you add a non-static method Process to you class, you can do something like this:
SignalProcessor* sp[MAX_SIGNALS];
static void SignalProcessor::OnMySignal(int sig_num)
{
printf("Caught %d signal\n", sig_num);
if (0 < sp[sig_num])
sp[sig_num]->Process();
fflush(stdout);
return;
}
I do the equivalent with Windows thead procedures and other assorted callbacks, and RTX interrupts all the time. The only real gotchas are that the members have to be static (which you already figured out), and that you have to make sure your routine is set to use the standard C/system call calling convention. Sadly, how you do that is platform dependent. In Win32 it is with the "__stdcall" modifier.
Note that you can use the passback-in pointer paramteter to "convert" such calls into normal class method calls. Like so ("self_calling_callback" is the static method):
unsigned long __stdcall basic_thread::self_calling_callback (void *parameter) {
if (parameter) {
basic_thread * thread = reinterpret_cast<basic_thread *>(parameter);
thread->action_callback();
}
return 0;
// The value returned only matters if someone starts calling GetExitCodeThread
// to retrieve it.
}
basic_thread::basic_thread () {
// Start thread.
m_Handle = CreateThread(NULL,
0,
self_calling_callback,
(PVOID)this,
0,
&m_ThreadId );
if( !IsHandleValid() )
throw StartException("CreateThread() failed", GetLastError());
}