A C++11 wrapper of pthread library, inspired by c++11 <thread>
.
It's a header-only library, and only requires compiler which supports C++11. (eg. gcc 4.8)
See examples in test to learn how it works.
Here we'll give some simple examples, use cxxpthread::Thread
need 2 or 3 steps:
-
- create
-
- join
-
- getResult() or getExitCode()
void f(int, int&);
int i, j;
Thread t(f, i, std::ref(j));
struct Foo {
void operator(int, int&);
};
Foo foo;
int i, j;
Thread t(foo, i, std::ref(j));
// NOTE: pass foo to Thread constructor means pass a copy of foo
struct Foo {
void f(int, int&);
};
Foo foo;
int i, j;
Thread t(&Foo::f, &foo, i, std::ref(j));
After Thread
object t
was created, you must call t.join()
later, which internally calls pthread_join()
and save result of pthread_exit
.
This step is not necessary, but if you want to get return value or exit code of thread function, you need it.
int f() { return 100; }
Thread t(f);
t.join();
auto p = t.getResult<int>(t); // p is std::unique_ptr<int> object
NOTE
- If you don't call
Thread::getResult<T>()
for a function with return value, it will cause memory leak! Thread::getResult<T>()
can only be called once!- If
T
is not proper, it may cause memory leak, likeint* p = new int(1); delete (double*)p;
; T
must be moveable.
void f() { Thread::exit(1); }
Thread t(f);
t.join();
long exit_code = t.getExitCode(); // 1