Library of Assembled Shared Sources
ThreadFun Class Reference

library to run (member) functions in a thread More...

#include <thread_fun.h>

Detailed Description

library to run (member) functions in a thread

Author
[Bramz]

With these objects/functions, you can run (member) functions in threads instead of calling them directly. you even can specify the arguments to be used. Let's illustrate this with a simple example:

void foo(int iNumber, const std::string& iText);
// direct call
foo(5, "hello");
// through thread
threadFun(foo, 5, "hello")->run();

threadFun2 allocates a new thread with the necessary information to call the function, then creates and runs the thread. It returns a pointer to the allocated thread. If you do nothing, the thread runs in detached mode and will kill itself at completion (so you don't have to call delete on thread yourself. So you even don't have to catch the return value. However, if you want to run it in joinable, you'll have delete the thread yourself. DO NOT FORGET THIS! Maybe we should do something about this situation?

// run two threads at the same time.
std::unique_ptr<Thread> a(threadFun(foo, 5, "hello", threadJoinable));
std::unique_ptr<Thread> b(threadFun(foo, 6, "world!", threadJoinable));
a->run();
b->run();
a->join();
b->join();

You can also call member functions of specific objects in the thread, both const as non-const member functions.

class Bar
{
void fun(float iValue) const;
void beer();
};
Bar bar;
std::unique_ptr<Thread> a(threadFun(bar, Bar::fun, 3.14, threadJoinable));
std::unique_ptr<Thread> b(threadFun(bar, Bar::beer, threadJoinable));
a->run();
b->run();
a->join();
b->join();

Limitations:

  • the functions can't have return values, or they are ignored (who should they pass it through to, anyway?)
  • You can't have more than 15 arguments (unless you tweak the prebuild ;)
Warning
Only ThreadFun0 and ThreadFun1 are partially tested.

The documentation for this class was generated from the following files: