Skip to content

Instantly share code, notes, and snippets.

@fffaraz
Created June 5, 2015 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fffaraz/83a1a133f1d257a6a98f to your computer and use it in GitHub Desktop.
Save fffaraz/83a1a133f1d257a6a98f to your computer and use it in GitHub Desktop.
C++ pthread
class C
{
public:
void *hello(void)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
class MyThreadClass
{
public:
MyThreadClass() {/* empty */}
virtual ~MyThreadClass() {/* empty */}
/** Returns true if the thread was successfully started, false if there was an error starting the thread */
bool StartInternalThread()
{
return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
}
/** Will not return until the internal thread has exited. */
void WaitForInternalThreadToExit()
{
(void) pthread_join(_thread, NULL);
}
protected:
/** Implement this method in your subclass with the code you want your thread to run. */
virtual void InternalThreadEntry() = 0;
private:
static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}
pthread_t _thread;
};
static void* execute_print(void* ctx) {
c* cptr = (c*)ctx;
cptr->print();
return NULL;
}
void func() {
...
pthread_create(&t1, NULL, execute_print, &c[0]);
...
}
struct Foo
{
void * run() { /* ... use state ... */ }
/* ... state ... */
};
Foo x;
pthread_t pt;
// start a new execution context with x.run():
pthread_create(&pt, NULL, FooInvoker, &x);
extern "C" void * FooInvoker(void * p)
{
return static_cast<Foo*>(p)->run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment