Last active
September 13, 2024 18:10
-
-
Save stpettersens/91a859b043ae9f7d78bb9ea6ec5c1e51 to your computer and use it in GitHub Desktop.
Demonstrate threads and signals in D (dlang).
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
// Demonstrate threads and signals in D (dlang). | |
import std.stdio; | |
import core.thread; | |
shared bool g_Running = true; | |
version(Windows) { | |
import core.sys.windows.windows; | |
extern(Windows) BOOL CtrlHandler(DWORD fdwCtrlType) nothrow { | |
if (fdwCtrlType == CTRL_C_EVENT) { | |
g_Running = false; | |
return TRUE; | |
} | |
return FALSE; | |
} | |
} | |
else version(Posix) { | |
import core.sys.posix.signal; | |
extern(C) void handleInterrupt(int signalNumber) nothrow @nogc { | |
g_Running = false; | |
} | |
} | |
void doSomething() { | |
while (g_Running) | |
writeln("Thread running!"); | |
writeln("Thread stopped."); | |
} | |
int main() { | |
version(Windows) { | |
SetConsoleCtrlHandler(&CtrlHandler, TRUE); | |
} | |
else version(Posix) { | |
signal(SIGINT, &handleInterrupt); | |
} | |
auto thread = new Thread(() { | |
doSomething(); | |
}); | |
thread.start(); | |
writeln("Thread joining..."); | |
thread.join(); | |
writeln("Terminating program..."); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment