Last active
March 6, 2018 19:12
-
-
Save viperscape/ca27daeb144d2a128ebf1dbeb6229567 to your computer and use it in GitHub Desktop.
cross os threading example
This file contains hidden or 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
void* thread (void* (callback)(void* data), void* data); | |
void join (void* p); | |
#ifdef _WIN32 | |
#include <windows.h> | |
void* thread (void* (callback)(void* data), void* data) { | |
HANDLE p = CreateThread(NULL, 0, callback, data, 0, NULL); | |
return p; | |
} | |
void join (void* p) { | |
if (p) { | |
WaitForSingleObject(p, INFINITE); | |
CloseHandle((HANDLE) p); | |
} | |
} | |
#else | |
#include <pthread.h> | |
#include <unistd.h> | |
void* thread (void* (callback)(void* data), void* data) { | |
pthread_t p; | |
pthread_create(&p, NULL, callback, data); | |
return (void*)p; | |
} | |
void join (void* p) { | |
pthread_join((pthread_t) p, NULL); | |
} | |
#endif |
This file contains hidden or 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
#include <stdio.h> | |
#include "thread.h" | |
void* hello_world(void* data) { | |
printf("hello %s\n", data); | |
} | |
int main () { | |
char* world = "world"; | |
void* server = thread(hello_world, (void*) world); | |
join(server); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment