我有一个 C++ 代码,它使用 _beginthreadex() Windows 方法在线程中执行函数。现在我想将其移植到 WinRT 组件以将其包含在 Windows Phone 应用程序中。但Windows Phone不支持_beginthreadex()。我该怎么做?
我的功能是:
bool doesWordAppearInDictionarry(char* word);
我的计算机上有 4 个核心,因此我想并行执行该函数的 4 个副本(同时在字典中搜索 4 个不同的单词)。
I read (here http://msdn.microsoft.com/en-us/library/windows/apps/windows.system.threading.threadpool.runasync.Aspx) and (here http://www.getcodesamples.com/src/EBA6140) about Windows::System::Threading::WorkItemHandler
, ThreadPool
's and 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;
}
}
该解决方案基于堆栈溢出答案(here https://stackoverflow.com/questions/15839895/porting-createthread-calls-to-win8-winrt-app)其中讨论了(this http://blogs.msdn.com/b/shawnhar/archive/2012/03/12/createthread-for-windows-8-metro.aspx?PageIndex=2) 博客。该博客包含对线程的完整模拟,包括 CreateThread() Win32 API,在线程运行时访问线程并在线程之间共享内存。我的解决方案是完整模拟器的简化案例。
附注调用者方法必须等待线程使用WaitForSingleObjectEx(
) 方法而不是WaitForSingleObject()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)