I'm trying to develop a thread abstraction (POSIX thread and thread from the Windows API), and I would very much like it to be able to start them with a method pointer, and not a function pointer.
What I would like to do is an abstraction of thread being a class with a pure virtual method "runThread", which would be implanted in the future threaded class.
I don't know yet about the Windows thread, but to start a POSIX thread, you need a function pointer, and not a method pointer.
And I can't manage to find a way to associate a method with an instance so it could work as a function.
I probably just can't find the keywords (and I've been searching a lot), I think it's pretty much what Boost::Bind() does, so it must exist.
Can you help me ?
Don't do this. Use boost::thread.
With boost::thread you can start threads with any functor of signature void(), so you can use std::mem_fun and std::bind1st, like in
struct MyAwesomeThread
{
void operator()()
{
// Do something with the data
}
// Add constructors, and perhaps a way to get
// a result back
private:
// some data here
};
MyAwesomeThread t(parameters)
boost::thread(std::bind1st(std::mem_fun_ref(&t::operator()), t));
EDIT: If you really want to abstract POSIX threads (it is not hard), you can do (I leave you the initialization of the pthread_attr)
class thread
{
virtual void run() = 0; // private method
static void run_thread_(void* ptr)
{
reinterpret_cast<thread*>(ptr)->run();
}
pthread_t thread_;
pthread_attr_t attr_;
public:
void launch()
{
pthread_create(&thread_, &attr_, &::run_thread_, reinterpret_cast<void*>(this));
}
};
but boost::thread is portable, flexible and very simple to use.
You really should use Boost.Thread. But if you can't and the call to start a thread allows you to pass a parameter to your thread function, a common idiom is to have a stand-alone or static member function which casts the parameter to an object pointer. e.g.
class Thread {
public:
void start() { start_thread(_work, this); } // whatever call starts a thread
void work() {} // does thread work
private:
static void _work(void* param) {
(reinterpret_cast<Thread*>(param))->work();
}
}
You need a C++ API for threading. Something like boost::thread (which is pretty much the same API that will be in the new C++). The OS thread API's are generally in C and you simply CAN'T pass non-static member function pointers to them, nor functors (which is what boost::bind creates).
Well, it's actually an exercise, and I don't have the right to use anything (not even Boost).
Of course I don't HAVE to do it that way (I only have to develop a thread abstraction), I just would like to : I used SFML thread abstraction once and I just loved it. It's such a sexy way to deal with it.
Ferruccio way seems good !
If the work() method is pure virtual, it can be implemented in any class implementing the thread abstraction... and it would work just fine, right ? (I'm not quite sure if it will, but according to my basic knowledge of C++, I guess it should ?)
Related
I wondered if there is a way to implement callbacks in C++ like it's possible in java?
To be more specific: To define the callback function directly when passing it to another function.
Something like this:
int main(void) {
...
myButton->addOnClickCallback(new myCallback(){
// do some stuff.
});
return 0;
}
I didn't find anything similar to this in C++, so I wondered if it's possible.
It would be nice for the sake of convenience :)
You use lambdas from C++11 further on:
myButton->addOnClickCallback([](){
// do some stuff.
});
That's the only direct way.
If that's not available, among other solutions, you can pass a pointer to a function, acquired by & operator (is not required), not new. Secondly, that function must be defined outside main:
myCallback() {
// do some stuff.
}
int main (void) {
myButton->addOnClickCallback(myCallback);
return 0;
}
Since lambdas are already covered in another answer, here is another solution (actually, a replica of Java thing):
#include <iostream>
struct Base {
virtual void process() = 0;
};
void want_callback(Base& b) {
b.process();
}
void foo() {
struct X : Base {
void process() {
std::cout << "Process\n";
}
} callback;
want_callback(callback);
}
You can also do this exactly the way Java does it: a class that needs to interact with another class does so by publishing an interface it expects the collaborator to implement. The class invokes methods on it's collaborator by calling methods on the callback interface.
I think of lambdas as generalizing function pointers from C than as callbacks. The standard library uses simple predicates as arguments to its algorithms and lambdas work great with those algorithms. When the communication back and forth between two collaborating objects becomes more involved, then you must pass in multiple lambdas: one for each interaction that is expected. Managing this pile of lambdas becomes cumbersome and using an interface starts to win out for comprehension and readability at that point.
For a single interaction that is "fire and forget" and the lifetime of the callback doesn't get messy, then lambdas work great. With classes implementing interfaces you can more directly control the lifetime of any dependent data and more directly express the nature of the interaction between the two objects.
This approach is exemplified by Sergey's code in his answer.
I am using a singleton class with a thread that calls into the singleton. I was asked during a review why I used the this pointer instead of the singleton instance.
My code with the suggested changes.
class myClass : public threadWrapper
{
public:
static myClass& instance()
{
static myClass instance;
return instance;
}
// This is the callback that I have implemented
static void callback(void *me)
{
if (me != NULL)
static_cast<myClass*>(me)->doCallback();
}
// This is the suggested callback
static void callback2(void *me)
{
instance().doCallback();
}
// caller gets instance and then calls initialise()
int initialise()
{
if (initialised)
return ERROR_ALREADY_INITIALISED;
// Initialise the class
// my thread startup call
// thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
// priority is a global value that difines the relative priority of the various threads.
threadWrapper::Initialise(priority, callback, this);
initialised = true;
}
private:
myClass() : initialised(false) {;}
void doCallback(void);
bool initialised;
static const int
}
So is there any significant difference in speed between the two?
The threadWrapper is mandated in the existing code base, and I'm not allowed to use boost.
My justification was that if we needed to make this not a singleton then fewer changes would be required.
The speed difference will be pretty much nonexistent.
As for code quality, Singletons are quite horrendous and I personally would chuck out both forms, especially in a threaded environment. Assuming that it's too late for that, however.
The thing is, if you're gonna pass in a pointer to the object, why not just not make that object global in the first place? And if you are, it should at least be strongly typed. And then, you're just ... wrapping a member method in a static method? Why bother? Anyone who has a pointer to the class can just call the method on it in the first place. This is just insane.
Edit: If you're stuck with the existing design, then the second version is definitely better than the first and no slower. Even if you have existing code that depends on the Singleton, then it's absolutely better to refactor what you can to not depend on it.
When writing C programs that need to share a file scope variable between the application and an interrupt routine/a thread/a callback routine, it is well-known that the variable must be declared volatile, or else the compiler may do incorrect optimizations. This is an example of what I mean:
int flag;
void some_interrupt (void)
{
flag = 1;
}
int main()
{
flag = 0;
...
/* <-- interrupt occurs here */
x = flag; /* BUG: the compiler doesn't realize that "flag" was changed
and sets x to 0 even though flag==1 */
}
To prevent the above bug, "flag" should have been declared as volatile.
My question is: how does this apply to C++ when creating a class containing a thread?
I have a class looking something like this:
class My_thread
{
private:
int flag;
static void thread_func (void* some_arg) // thread callback function
{
My_thread* this_ptr= (My_thread*)some_arg;
}
};
"some_arg" will contain a pointer to an instance of the class, so that each object of "My_thread" has its own thread. Through this pointer it will access member variables.
Does this mean that "this_ptr" must be declared as pointer-to-volatile data? Must "flag" be volatile as well? And if so, must I make all member functions that modify "flag" volatile?
I'm not interested in how a particular OS or compiler behaves, I am looking for a generic, completely portable solution.
EDIT: This question has nothing to do with thread-safety whatsoever!
The real code will have semaphores etc.
To clarify, I wish to avoid bugs caused by the compiler's unawareness of that a callback function may be called from sources outside the program itself, and therefore make incorrect conclusions about whether certain variables have been used or not. I know how to do this in C, as illustrated with the first example, but not in C++.
Well, that edit makes all the difference of the world. Semaphores introduce memory barriers. Those make volatile redundant. The compiler will always reload int flag after any operation on a semaphore.
Fred Larson already predicted this. volatile is insufficient in the absence of locks, and redudant in the presence of locks. That makes it useless for thread-safe programming.
From the function pointer signature I guess you are using the posix thread implementation for threads. I assume you want to know how to start off a thread using this API. First consider using boost thread instead. If not an option, I usually go for something like the following to get somewhat of that cosy Java readability.
class Runnable {
public:
virtual void run() = 0;
};
class Thread : public Runnable {
public:
Thread();
Thread(Runnable *r);
void start();
void join();
pthread_t getPthread() const;
private:
static void *start_routine(void *object);
Runnable *runner;
pthread_t thread;
};
And then something like this in the start_routine function:
void* Thread::start_routine(void *object) {
Runnable *o = (Runnable *)object;
o->run();
pthread_exit(NULL);
return NULL;
}
Now access to fields of classes extending the Runnable or Thread class need not be volatile since they are thread-local.
That said, sharing data between threads is more complex than using a volatile data member unfortunately if that is what you asked...
Read this article by Andrei Alexandrescu over at Dr. Dobbs, it might be relevant:
volatile - Multithreaded Programmer's Best Friend
From the intro to the article:
The volatile keyword was devised to
prevent compiler optimizations that
might render code incorrect in the
presence of certain asynchronous
events. For example, if you declare a
primitive variable as volatile, the
compiler is not permitted to cache it
in a register -- a common optimization
that would be disastrous if that
variable were shared among multiple
threads. So the general rule is, if
you have variables of primitive type
that must be shared among multiple
threads, declare those variables
volatile. But you can actually do a
lot more with this keyword: you can
use it to catch code that is not
thread safe, and you can do so at
compile time. This article shows how
it is done; the solution involves a
simple smart pointer that also makes
it easy to serialize critical sections
of code.
Some implementation of the fallback mechanism is given here for both Windows and Linux. Try this example:
typeReadFileCallback varCallback;
I was able to implement using that.
Is there a pattern that I may use for calling the required initialization and cleanup routines of an underlying (C) library? In my case, I would like to create the wrapper class so that it can be composed into other objects. The problem is that, when I destroy the wrapper class, the cleanup routines of the underlying library are called. That's fine until I instantiate multiple objects of my wrapper class. My question is what is the best way to really handle this situation? A static reference counter comes to mind, but I wanted to know if there were other potentially better options and the trades involved.
If the initialization can be called before main starts, and cleanup called after main ends, this little trick (hack?) might work for you:
#include <iostream>
// C library initialization routine
void init() {std::cout << "init\n";}
// C library cleanup routine
void fini() {std::cout << "fini\n";}
// Put this in only one of your *.cpp files
namespace // anonymous
{
struct Cleaner
{
Cleaner() {init();}
~Cleaner() {fini();}
};
Cleaner cleaner;
};
int main()
{
std::cout << "using library\n";
}
Output:
init
using library
fini
It uses (abuses?) the fact that constructors for static objects are called before main, and that destructors are called after main. It's like RAII for the whole program.
Not everything has to be a class. The Singleton pattern would let you turn this into a class, but it's really not buying you anything over global functions:
bool my_library_init();
void my_library_shutdown();
The first call returns true if the library was successfully initialized, the second just quietly does whatever needs to be done and exits. You can add whatever reference counting or thread tracking type stuff behind these interfaces you like.
Also, don't neglect the possibility that your library may be able to do all of this transparently. When the first library function is called, could it detect that it is not initialized yet and set everything up before doing the work? For shutdown, just register the resources to be destroyed with a global object, so they are destroyed when the program exits. Doing it this way is certainly trickier, but may be worth the usability benefit to your library's callers.
I have seen a lot of Singleton talk, so I can only recommend a look at Alexandrescu's work.
However I am not sure that you really need a Singleton there. Because if you do, you assume that all your calls are going to share the state... is it the case ? Do you really wish when you call the library through a different instance of Wrapper to get the state in which the last call set it ?
If not, you need to serialize the access, and reinitialize the data each time.
class Wrapper
{
public:
Wrapper() { lock(Mutex()); do_init_c_library(); }
~Wrapper() { do_clean_up_c_library(); unlock(Mutex()); }
private:
static Mutex& Mutex() { static Mutex MMutex; return MMutex; }
}; // class Wrapper
Quite simple... though you need to make sure that Mutex is initialized correctly (once) and live until it's not needed any longer.
Boost offers facilities for the once issue, and since we use a stack based approach with MMutex it should not go awry... I think (hum).
If you can change the library implementation, you could have each call to one of the library's functions access a singleton which is created on first use.
Or you put a global/static variable into the library which initializes it during construction and shuts it down during destruction. (That might become annoying if the library uses global variables itself and the order of initialization/shutdown conflicts with them. Also, linkers might decide to eliminate unreferenced globals...)
Otherwise, I don't see how you want to avoid reference counting. (Note, however, that it has the drawback of possibly creating multiple init/shutdown cycles during the program's lifetime.)
If your set of C library routines is not too large, you can try combining the Singleton and Facade patterns so that C library routines are only invoked via the Facade. The Facade ensures the initialization and cleanup of the C library. Singleton insures that there is only one instance of the Facade.
#include <iostream>
// C library initialization and cleanup routines
void init() {std::cout << "init\n";}
void fini() {std::cout << "fini\n";}
// C library routines
void foo() {std::cout << "foo\n";}
void bar() {std::cout << "bar\n";}
class Facade // Singleton
{
public:
void foo() {::foo();}
void bar() {::bar();}
static Facade& instance() {static Facade instance; return instance;}
private:
Facade() {init();}
~Facade() {fini();}
};
// Shorthand for Facade::instance()
inline Facade& facade() {return Facade::instance();}
int main()
{
facade().foo();
facade().bar();
}
Output:
init
foo
bar
fini
I'm wondering the best way to start a pthread that is a member of a C++ class? My own approach follows as an answer...
This can be simply done by using the boost library, like this:
#include <boost/thread.hpp>
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
boost::thread* pThread = new boost::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
Notes:
This uses an ordinary class member function. There is no need to add extra, static members which confuse your class interface
Just include boost/thread.hpp in the source file where you start the thread. If you are just starting with boost, all the rest of that large and intimidating package can be ignored.
In C++11 you can do the same but without boost
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
std::thread * pThread = new std::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
I usually use a static member function of the class, and use a pointer to the class as the void * parameter. That function can then either perform thread processing, or call another non-static member function with the class reference. That function can then reference all class members without awkward syntax.
You have to bootstrap it using the void* parameter:
class A
{
static void* StaticThreadProc(void *arg)
{
return reinterpret_cast<A*>(arg)->ThreadProc();
}
void* ThreadProc(void)
{
// do stuff
}
};
...
pthread_t theThread;
pthread_create(&theThread, NULL, &A::StaticThreadProc, this);
I have used three of the methods outlined above.
When I first used threading in c++ I used static member functions, then friend functions and finally the BOOST libraries. Currently I prefer BOOST. Over the past several years I've become quite the BOOST bigot.
BOOST is to C++ as CPAN is to Perl. :)
The boost library provides a copy mechanism, which helps to transfer object information
to the new thread. In the other boost example boost::bind will be copied with a pointer, which is also just copied. So you'll have to take care for the validity of your object to prevent a dangling pointer. If you implement the operator() and provide a copy constructor instead and pass the object directly, you don't have to care about it.
A much nicer solution, which prevents a lot of trouble:
#include <boost/thread.hpp>
class MyClass {
public:
MyClass(int i);
MyClass(const MyClass& myClass); // Copy-Constructor
void operator()() const; // entry point for the new thread
virtual void doSomething(); // Now you can use virtual functions
private:
int i; // and also fields very easily
};
MyClass clazz(1);
// Passing the object directly will create a copy internally
// Now you don't have to worry about the validity of the clazz object above
// after starting the other thread
// The operator() will be executed for the new thread.
boost::thread thread(clazz); // create the object on the stack
The other boost example creates the thread object on the heap, although there is no sense to do it.