Skip to content

Instantly share code, notes, and snippets.

@aferust
Last active September 23, 2023 21:44
Show Gist options
  • Save aferust/898a96fdfe23e72ce14685c7e0250e56 to your computer and use it in GitHub Desktop.
Save aferust/898a96fdfe23e72ce14685c7e0250e56 to your computer and use it in GitHub Desktop.
BetterC threadpool
// WIP
import dvector;
import deimos.uv;
struct UVThread {
alias CBDelegate = void delegate(void*, void*) @nogc nothrow;
alias CBFunPtr = void function(void*, void*) @nogc nothrow;
uv_thread_t thread;
CBDelegate threadDelg;
CBFunPtr threadFunc;
void* udt;
bool running;
@nogc nothrow:
this(CBDelegate tf){
threadDelg = tf;
uv_thread_create(&thread, (&UVThread._wrapDel).funcptr, (&UVThread._wrapDel).ptr);
}
this(CBFunPtr tf, void* udt){
threadFunc = tf;
this.udt = udt;
uv_thread_create(&thread, (&UVThread._wrapFun).funcptr, (&UVThread._wrapFun).ptr);
}
extern (C) void _wrapDel(void* arg){
running = true;
threadDelg(uv_thread_self(), arg);
running = false;
}
extern (C) void _wrapFun(void*){
running = true;
threadFunc(uv_thread_self(), udt);
running = false;
}
void start(){
uv_thread_join(&thread);
}
}
struct UVThreadPool {
Dvector!UVThread pool;
@nogc nothrow:
void put(UVThread thr){
pool.pushBack(thr);
thr.start;
}
void start(){
foreach(ref thr; pool){
if(!thr.running) thr.start();
}
}
~this(){
pool.clear();
}
}
@nogc nothrow:
void thread_cb(void* tid, void* arg) {
foreach(i; 0..3){
printf("hello thread: %p \n", tid);
Sleep(1000);
}
}
extern (C) int main() {
int userData = 13;
//void delegate(void*) @nogc nothrow myDlgt; // does not have to be extern (C)
//myDlgt.funcptr = &thread_cb;
//myDlgt.ptr = &userData;
auto tp1 = UVThread(&thread_cb, &userData);
auto tp2 = UVThread(&thread_cb, &userData);
auto tp3 = UVThread(&thread_cb, &userData);
//tp.start;
UVThreadPool pool;
pool.put(tp1);
printf("done?\n".ptr);
pool.put(tp2);
printf("done?\n".ptr);
pool.put(tp3);
printf("done?\n".ptr);
//pool.start;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment