gpt4 book ai didi

c++ - Windows.h 线程关联

转载 作者:可可西里 更新时间:2023-11-01 11:13:26 27 4
gpt4 key购买 nike

除了输出不是我期望的那样,下面的代码确实可以编译和运行。我希望程序创建 n 个线程(取决于可用多核的数量)并运行程序末尾的一个简单例程以输出

“测试:”

后跟数字 1-10。相反,我得到的是一个输出,它确实写了一些数字,但它最多不会超过两个,而且函数 threadmain 似乎没有完全在一个线程上运行,但它在其他方面输出了一些测试:012。我知道多线程会破坏输出,但我应该在屏幕上的某处看到数字 3、4、5、6、7、8、9,但它没有显示。

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <cmath>
#include <iostream>

HANDLE *m_threads = NULL;
static DWORD_PTR WINAPI threadMain(void* p);

DWORD_PTR GetNumCPUs()
{
SYSTEM_INFO m_si = {0, };
GetSystemInfo(&m_si);
return (DWORD_PTR)m_si.dwNumberOfProcessors;
}

CRITICAL_SECTION g_crit_sec;
static int g_start = 0;

int main(int argc, char **args)
{
DWORD_PTR c = GetNumCPUs();

m_threads = new HANDLE[c];

InitializeCriticalSectionAndSpinCount(&g_crit_sec, 0x80000400);

for(DWORD_PTR i = 0; i < c; i++)
{
DWORD_PTR m_id = 0;
DWORD_PTR m_mask = 1 << i;

m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain, (LPVOID)i, NULL, &m_id);
SetThreadAffinityMask(m_threads[i], m_mask);

//wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask);
}

return 0;
}
static DWORD_PTR WINAPI threadMain(void* p)
{
double result = 0.0;

for (int i = 0; i < 10; i++)
{
std::cout<<"testing: "<<i<<std::endl;
//result = result + sin(i) * tan(i);
}

return 0;
}

最佳答案

您的应用程序在您的线程完成运行之前终止。在启动线程后,在您的主函数中调用 Sleep() 或更合适的 WaitForMultipleObjects() 调用,如下所示:

int main(int argc, char **args)
{
DWORD_PTR c = GetNumCPUs();

m_threads = new HANDLE[c];

InitializeCriticalSectionAndSpinCount(&g_crit_sec, 0x80000400);

for(DWORD_PTR i = 0; i < c; i++)
{
DWORD_PTR m_id = 0;
DWORD_PTR m_mask = 1 << i;

m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain, (LPVOID)i, NULL, (LPDWORD)&m_id);
SetThreadAffinityMask(m_threads[i], m_mask);

//wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask);
}

// Waits for all started threads to complete:
WaitForMultipleObjects(c, m_threads, TRUE, INFINITE);

return 0;
}

关于c++ - Windows.h 线程关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13459714/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com