Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active August 23, 2017 03:16
Show Gist options
  • Save Porges/3348ab928ebc18e00fcd618a5a82f1d4 to your computer and use it in GitHub Desktop.
Save Porges/3348ab928ebc18e00fcd618a5a82f1d4 to your computer and use it in GitHub Desktop.
Helper for native threadpool use
#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