我的任务是编写一个多线程程序,通过动态确定机器上可以运行的最大线程数来解决数独难题,然后分配那么多线程以从文件中获取所有数独难题中的单个难题。
像这样:我们确定该计算机上可以运行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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句