Created
June 5, 2015 20:38
-
-
Save fffaraz/83a1a133f1d257a6a98f to your computer and use it in GitHub Desktop.
C++ pthread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void* execute_print(void* ctx) { | |
c* cptr = (c*)ctx; | |
cptr->print(); | |
return NULL; | |
} | |
void func() { | |
... | |
pthread_create(&t1, NULL, execute_print, &c[0]); | |
... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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