gpt4 book ai didi

c++ - 这个线程池/多核模拟有什么问题

转载 作者:太空宇宙 更新时间:2023-11-04 13:57:54 25 4
gpt4 key购买 nike

大家好。我一直在尝试制作一种线程池,用于模拟多核处理器,其中我有许多线程一直在运行(核心),我稍后会分派(dispatch)它们来处理一个(暂时固定)功能。让线程始终运行的想法是我没有线程创建/销毁开销。我现在做的事情存在三个问题。首先,结果都是错误的。二、测时函数报0ms第三,程序在退出时调用 abort。这是我正在使用的代码:

    auto fakeExpensiveOperation = [](int i) -> float
{
Sleep(10);
return sqrt(i);
};

// Performance test
int size = 4000;
float* out = new float[size];

#define THREAD_RUNNING 0
#define THREAD_FINISHED (1 << 0)
#define THREAD_EXIT (1 << 1)
#define THREAD_STALL (1 << 2)

const int coreCount = 8;
thread cores[coreCount];
atomic<unsigned int> msgArray[coreCount]; for (auto& msg : msgArray) msg.store(THREAD_STALL);

auto kernel = [out, &fakeExpensiveOperation](int idx){ out[idx] = fakeExpensiveOperation(idx); };
for (int i = 0; i < coreCount; i++)
{
cores[i] = thread([&msgArray, i, kernel]()
{
while (true)
{
unsigned int msg = msgArray[i].load();

if((msg & THREAD_STALL) == THREAD_STALL)
continue;

if ((msg & THREAD_EXIT) == THREAD_EXIT)
break;

if ((msg & THREAD_RUNNING) == THREAD_RUNNING)
{
int idx = (msg >> 3) + i;

// Do the function
kernel(idx);

msgArray[i].store(THREAD_FINISHED);
}
}
});
}

auto t2 = time_call([&]()
{
for (int i = 0; i < size; i += coreCount)
{
for (int n = 0; n < coreCount; n++)
{
if((msgArray[n].load() & THREAD_RUNNING) == THREAD_RUNNING) continue; // The core is still working

unsigned int msg = THREAD_RUNNING;
msg |= (i << 3);
msgArray[n].store(msg);
}
}
});
for (int n = 0; n < coreCount; n++) msgArray[n].store(THREAD_EXIT);

cout << "sqrt 0 : " << out[0] << endl;
cout << "sqrt 1 : " << out[1] << endl;
cout << "sqrt 2 : " << out[2] << endl;
cout << "sqrt 4 : " << out[4] << endl;
cout << "sqrt 16 : " << out[16] << endl;

cout << "Parallel : " << t2 << endl;
system("pause");
delete[] out;
return 0;

我真的没脑子了。谁能指出这里出了什么问题?

编辑:我做了我提到的更改,但仍然得到错误的值。我更改了标志的值,并在创建线程后将其分离。

最佳答案

我可能是错的,(我对 C++11 线程的东西不是很熟悉)但看起来你正在运行一个线程 cores[i] = thread([&msgArray, i, kernel]( ) 然后等待该线程完成。然后创建下一个线程。本质上使其成为单线程。

我也喜欢用它来为 C++11 计时

std::chrono::time_point<std::chrono::system_clock> start, end;

start = std::chrono::system_clock::now();

// Do Stuff

end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds_d1 = end-start;
std::time_t end_time_d1 = std::chrono::system_clock::to_time_t(end);
std::cout << "elapsed time: " << elapsed_seconds_d1.count() << "s\n";

关于c++ - 这个线程池/多核模拟有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623024/

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