如何在 WinRT 下的并行线程中执行 c++ 函数

How to execute c++ function in a parallel thread under WinRT?

本文关键字:线程 执行 c++ 函数 并行 WinRT      更新时间:2023-10-16

我有一个C++代码,它使用_beginthreadex()Windows方法在线程中执行函数。现在我想将其移植到 WinRT 组件以将其包含在 Windows Phone 应用程序中。但是Windows Phone不支持_beginthreadex()。我该怎么做?

我的函数是:

bool doesWordAppearInDictionarry(char* word);

我的计算机上有 4 个内核,所以我想并行执行此功能的 4 个副本(同时在字典中搜索 4 个不同的单词)。

我读到(这里)和(这里)关于Windows::System::Threading::WorkItemHandlerThreadPoolIAsyncAction但是提供的示例激活托管代码,并且不调用本机函数。

正在寻找的是一个干净的解决方案(最少的代码行数),它将取代我当前的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()