我的任务是编写一个多线程程序,通过动态确定可以在机器上运行的最大线程数来解决一组sudoku难题,然后分配那么多线程从文件中抓取单个谜题和所有sudoku谜题。
比如:我们已经确定了8个线程可以在这台机器上运行,所以我们将分配8个线程。然后,这8个线程轮流从堆中抓取单个sudoku难题,并将它们写到一个新的文件中,并给出解决方案。
到目前为止,我所拥有的是一个完全工作的代码,用于抓取第一个谜题,解决问题,并将其写入解决方案文件。但我需要使它多线程,并让它为所有其他的谜题也这样做。我有一个类,它保存sudoku的拼图数据,名为SudokuGrid,它有9x9数组。
我正在为每个线程分配线程和类的概念,我认为我可以生成一个数组来保存线程,但是我如何分配相应的类实例呢?,我相信每个线程都需要一个实例,因为它们将处理自己的不同的谜题。我应该用std::线程来做这个。
发布于 2020-10-16 08:16:09
直接回答你的问题这不是帮助您解决谜题的逻辑,而是帮助您为方法分配和管理线程),这是一个关于如何设置对象以在不同线程上执行某些工作的极简示例:
#include <iostream>
#include <random>
#include <thread>
struct Foo
{
int count;
void Bar (int n)
{
count = 0;
for (int i = 0; i < n; ++i)
count += std::rand() % n;
}
};
void SetUpMultiThreading (std::vector<Foo> & foo)
{
int n = foo.size();
std::vector<std::thread> threads(n);
// the below (2*i+5) is just some mock data input
for (int i = 0; i < n; ++i)
threads[i] = std::thread(&Foo::Bar, std::ref(foo[i]), 2*i+5);
// Note that without std::ref (or a custom wrapper instead)
// then the foo element would be copied to the std::thread
// function, so you'd lose access to the results
for (auto & t : threads)
t.join();
}
void CheckWork (const std::vector<Foo> & foo)
{
for (auto & f : foo)
std::cout << f.count << std::endl;
}
int main ()
{
srand(time(NULL));
const int n = 8;
std::vector<Foo> foo(n);
SetUpMultiThreading(foo);
CheckWork(foo);
}
https://stackoverflow.com/questions/64382077
复制相似问题