Last active
August 23, 2017 03:16
-
-
Save Porges/3348ab928ebc18e00fcd618a5a82f1d4 to your computer and use it in GitHub Desktop.
Helper for native threadpool use
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 <Windows.h> | |
#include <functional> | |
#include <memory> | |
#include <system_error> | |
void CALLBACK InvokeFunction(PTP_CALLBACK_INSTANCE, void* context, PTP_WORK) | |
{ | |
std::unique_ptr<std::function<void()>> owned{ static_cast<std::function<void()>*>(context) }; | |
(*owned)(); | |
} | |
void QueueBackgroundWork(std::function<void()> func) | |
{ | |
auto ptr = std::make_unique<std::function<void()>>(std::move(func)); | |
auto work = CreateThreadpoolWork(InvokeFunction, ptr.get(), nullptr); | |
if (work == nullptr) | |
{ | |
auto lastErr = GetLastError(); | |
throw std::system_error{ static_cast<int>(lastErr), std::system_category() }; | |
} | |
else | |
{ | |
ptr.release(); | |
} | |
SubmitThreadpoolWork(work); | |
CloseThreadpoolWork(work); | |
} | |
#include <iostream> | |
#include <thread> | |
int main() | |
{ | |
QueueBackgroundWork([]() { std::cout << "hello from background thread" << std::endl; }); | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment