如何在 WinRT 下的并行线程中执行 c++ 函数
How to execute c++ function in a parallel thread under WinRT?
我有一个C++代码,它使用_beginthreadex()Windows方法在线程中执行函数。现在我想将其移植到 WinRT 组件以将其包含在 Windows Phone 应用程序中。但是Windows Phone不支持_beginthreadex()。我该怎么做?
我的函数是:
bool doesWordAppearInDictionarry(char* word);
我的计算机上有 4 个内核,所以我想并行执行此功能的 4 个副本(同时在字典中搜索 4 个不同的单词)。
我读到(这里)和(这里)关于Windows::System::Threading::WorkItemHandler
,ThreadPool
和IAsyncAction
但是提供的示例激活托管代码,并且不调用本机函数。
正在寻找的是一个干净的解决方案(最少的代码行数),它将取代我当前的Windows桌面代码:
for (int i=0; i<4; i++){
tInfo[i].id = (HANDLE)_beginthreadex( NULL, stack_size, doesWordAppearInDictionarry,tInfo, 0, word[i]);
}
for (int i=0; i<4; i++){
WaitForSingleObject( tInfo[i].id, INFINITE );
CloseHandle(tInfo[i].id);
}
下面是一个简短的解决方案:使用 WinRT API 模拟 _beginthreadex() 的几行代码。
using namespace Platform;
using namespace Windows::System::Threading;
_Use_decl_annotations_ HANDLE WINAPI _beginthreadex(LPSECURITY_ATTRIBUTES unusedThreadAttributes, SIZE_T unusedStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD unusedThreadId){
// Create a handle for the new thread.
HANDLE threadHandle = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
if (!threadHandle)
return nullptr;
try{
auto workItemHandler = ref new WorkItemHandler([=](IAsyncAction^){
lpStartAddress(lpParameter);
SetEvent(threadHandle); // Signal that the thread has completed (assuming this handle was not destroyed by the caller due to time-out).
}, CallbackContext::Any);
ThreadPool::RunAsync(workItemHandler, WorkItemPriority::High, WorkItemOptions::TimeSliced);
return threadHandle; // Return the handle to the caller (he can wait for this handle until thread terminates).
}
catch (...){
CloseHandle(threadHandle); // Clean up if thread creation fails.
return nullptr;
}
}
此解决方案基于讨论(此)博客的堆栈溢出答案(此处)。该博客包括线程的完整仿真,包括 CreateThread() Win32 api,在线程运行时访问线程并在线程之间共享内存。我的解决方案是完整模拟器的简化案例。
附言调用方方法必须使用 WaitForSingleObjectEx(
) 方法而不是 WaitForSingleObject()
相关文章:
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- C++线程:如何在一个线程仍在运行时阻止另一个线程执行 (Win32)
- 在给定时间段内,线程执行的指令数量是否有最小数量?
- 如何在C++中停止线程执行
- 为什么Win API线程执行函数,而标准线程则没有
- 线程执行在IDE中和C 中的EXE应用程序中是否有所不同
- 从线程执行的函数中返回结构数组
- 为什么在从线程执行方法时使用QMetaObject::invokeMethod
- 只有一个线程执行 CUDA 内核
- C++ 多线程:执行顺序
- async_connect()超时,多个线程执行io_service.run()
- 是否可以将线程执行转移到另一个线程?
- 具有随机数总和的多线程执行时间
- 如何 在没有 Boost 的情况下将 C++ 成员函数作为线程执行
- openMP 在自定义容器中从 2 到 4 个线程执行二进制搜索时速度变慢
- 如何使生成的线程拖延足够长的时间以使生成线程执行某些操作
- 远程线程执行
- C++中的基本多线程(执行顺序)
- 线程池中的C++线程执行顺序
- 锁定由不同线程执行的多个函数