如何:创建手动任务队列
示例
您可能想要显式控制用于任务队列工作和完成的线程。 在这些情况下,可以创建手动任务队列并自行对调用进行调度。 如果使用的是手动任务队列,则必须确保它们也可以抽取 Windows 消息队列。
下面示例演示了如何创建一个手动抽取的任务队列。 它将创建两个 STL 线程,调度用于工作端口和完成端口的调用。
void CreatingTaskQueueWithManualThreads()
{
// Create a manual task queue.
XTaskQueueHandle queue;
HRESULT hr = XTaskQueueCreate(
XTaskQueueDispatchMode::Manual,
XTaskQueueDispatchMode::Manual,
&queue);
if (FAILED(hr))
{
printf("Creating queue failed: 0x%x\r\n", hr);
return;
}
// We create threads to pump the queue: one thread for the work port
// and one thread for the completion port.
std::thread workThread([queue]
{
// XTaskQueueDispatch returns false when there's nothing to
// dispatch. Here, we wait forever for something new to come
// in. This will return false only if the queue is being
// terminated.
while (XTaskQueueDispatch(queue, XTaskQueuePort::Work, INFINITE));
});
std::thread completionThread([queue]
{
// XTaskQueueDispatch returns false when there's nothing to
// dispatch. Here, we wait forever for something new to come
// in. This will return false only if the queue is being
// terminated.
while (XTaskQueueDispatch(queue, XTaskQueuePort::Completion, INFINITE));
});
SubmitCallbacks(queue);
// Wait a while for the callbacks to run.
Sleep(1000);
// Terminating the queue will cause a waiting XTaskQueueDispatch to return
// false.
XTaskQueueTerminate(queue, true, nullptr, nullptr);
workThread.join();
completionThread.join();
}