问题描述
我的任务是编写一个多线程程序,通过动态确定机器上可以运行的最大线程数来解决数独难题的集合,然后分配那么多线程以从文件中获取所有数独难题拼图。
类似的事情:我们确定这台计算机上可以运行8个线程,因此我们将分配8个线程。然后,这8个线程轮流从堆中抓取单个数独谜题并加以解决,然后将其写入带有解决方案的新文件中
到目前为止,我目前所掌握的是一个完全有效的代码,可以抓住第一个难题,进行解决并将其写入解决方案文件。但是我需要使它成为多线程的,并让它解决所有其他难题。我有一类保存名为SudokuGrid的数独谜题数据的类,该类具有9x9数组。
我正在为分配线程和为每个线程分配一个类的概念而苦苦挣扎,我想我可以生成一个数组来保存线程,但是我该如何分配相应的类实例呢?相信每个线程都需要一个实例,因为它们将处理各自不同的难题。我应该为此使用std :: thread。
解决方法
要直接解决您的问题(即,不能帮助您解决难题的逻辑,而只是帮助您分配和管理方法的线程),这是一个简单的示例,说明了如何设置对象来完成某些工作在不同的线程上:
#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);
}