2015-10-07 3 views
0

Это многопоточная программа, которая считывает матрицу 9x9 и проверяет, является ли она действительной судоку или нет. Я читаю и сохраняю ввод в двухмерном массиве. Для каждой строки я пытаюсь создать поток для строки, чтобы определить, содержит ли она цифры от 1 до 9. 9 общих потоков для проверки строк.многопоточность в алгоритме sudoku C++

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <thread> 

const int ROW = 9; 
const int COLUMN = 9; 

std::thread t[27]; 

using namespace std; 

void DisplayBoard (int board[ROW][COLUMN]); 
bool ReadBoard (char* filename, int board[ROW][COLUMN]); 
void CheckRows(vector <int> valid_ints, vector<int> board_row, bool &check_status); 
vector <int> stripList (int tmp, vector <int> valid_ints); 

int main(int argc, char * argv[]) { 

    int board[ROW][COLUMN]; 

    // If the user didn't provide a filename command line argument, 
    // print an error and exit. 
    if (argc <= 1) 
    { 
     cout << "Usage: " << argv[0] << " <Filename>" << endl; 
     //exit(1); 
    } 

    char *filename = argv[1]; 

    if (ReadBoard(filename, board)){ 
    DisplayBoard(board); 

    vector <int> valid_ints; 
    // Valid numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9 
    for(int i = 1; i <= 9; i++) 
     { 
     valid_ints.push_back(i); 
     } 

    vector <int> board_row; 

    bool check_status = true; 


    //iterate through the board 
    for (int i = 0; i < ROW; i++){ 
     for (int j = 0; j < COLUMN; j++){ 

     //pushed each number from row 
     board_row.push_back(board[i][j]); 

     } 

     //threading 
     //***** ERROR ***** 
     t[i] = thread(CheckRows, valid_ints, board_row, check_status); 

     // if valid ints aren't all striped, error in the row 
     if (check_status == false){ 
     cout << endl; 
     cout << "Invalid Row: " << i+1 << endl; 
     cout << "The input is not a valid Sudoku." << endl; 
     cout << endl; 
     exit(1); 
     } 
     else { 
     board_row.clear(); 
     valid_ints.clear(); 

     // Valid numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9 
     for(int z = 1; z <= 9; z++) 
     { 
      valid_ints.push_back(z); 
     } 
     } 
    } 

Вот мой чек ряд функций:

void CheckRows(vector <int> valid_ints, vector<int> board_row, bool &check_status){ 

    for (int i = 0; i < board_row.size(); i++){ 
    for (int j = 0; j < valid_ints.size(); j++){ 
     if (board_row[i] == valid_ints[j]) 
     //removes the board value and updates valid ints until all are found (valid) 
     valid_ints = stripList(board_row[i], valid_ints); 
    } 
    } 
    // invalid row 
    if (valid_ints.size() != 0) 
    check_status = false; 

} 

Ошибка Сейчас я получаю:

In file included from /usr/local/include/c++/5.1.0/thread:39:0, 
       from sudoku.cpp:5: 
/usr/local/include/c++/5.1.0/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::vector<int>, std::vector<int>, bool*))(std::vector<int>, std::vector<int>, bool&)>’: 
/usr/local/include/c++/5.1.0/thread:137:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<int>, std::vector<int>, bool&); _Args = {std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&, bool*}]’ 
sudoku.cpp:65:68: required from here 
/usr/local/include/c++/5.1.0/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<int>, std::vector<int>, bool*))(std::vector<int>, std::vector<int>, bool&)>’ 
     typedef typename result_of<_Callable(_Args...)>::type result_type; 
                  ^
/usr/local/include/c++/5.1.0/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<int>, std::vector<int>, bool*))(std::vector<int>, std::vector<int>, bool&)>’ 
     _M_invoke(_Index_tuple<_Indices...>) 

Я не уверен, что я делаю неправильно при создании потока. Пожалуйста помоги. Заранее спасибо.

+1

многопоточной без синхронизации ... Где вы не ждать результата вычисления, чтобы проверить результат ... Fix уже отсутствует ' const'/reference, прежде чем пытаться выполнить потоки, что не является простым доменом. – Jarod42

+0

Также обратите внимание, что бросание только фиксированного количества потоков не обязательно ускорит работу (но даже может ухудшить). Количество потоков должно быть сбалансировано с доступными ядрами ЦП. –

ответ

0

Попробуйте изменить строку:

t[i] = thread(CheckRows, valid_ints, board_row, std::ref(check_status)); 

См http://en.cppreference.com/w/cpp/thread/thread/thread

+1

Это не единственная проблема ... – Jarod42

+0

У меня было это подозрение, но у меня нет компилятора g ++ 5.1. –

+1

Есть несколько онлайн-компиляторов в качестве [ideone] (https://ideone.com/) или [coliru] (http://coliru.stacked-crooked.com/), ... – Jarod42

 Смежные вопросы

  • Нет связанных вопросов^_^