2014-01-13 27 views
0

好吧,我的代码可能有点杂乱 - 我是新手,很抱歉提前!基本上,代码读入一个2d数组中的文件,然后创建多个线程来对数组中多个行中的每个值执行计算。我遇到的问题是底部的for循环。它运行但不循环。我不知道为什么,并尝试了一些东西,但我是新来的,所以老实说不知道。所有的代码都在下面,任何帮助都会很大,非常感谢!在For循环中创建多个线程来处理2d数组

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
#include <stdlib.h> 
#include <time.h> 
#include <pthread.h> 

int threadArray[10][10]; 
int arrayVar[2]; 

using namespace std; 

void *calc(void *arg){ 

    int startPoint = arrayVar[0]; 
    int endPoint = arrayVar[1]; 
    int newArray[10][10]; 
    int calculated; 

    for (int i = startPoint ; i < endPoint; i++){ 
    for (int j = 0; j < 10; j++){ 
     calculated = (threadArray[i][j] * 2 + 4) * 2 + 4; 
     newArray[i][j] = calculated; 
    } 
    } 

    for (int i = startPoint; i < endPoint; i++){ 
     for (int j = 0; j < 10; j++){ 
     cout << newArray[i][j] << " "; 
     } 
     cout << endl; 
    } 
    return NULL; 
} 

int main(){ 

    int rc; 
    int start = 0; 
    int end; 

    ifstream numFile; 
    numFile.open("numbers.txt"); 

    if (numFile.is_open()){ 

    for (int row = 0; row < 10; row++){ 
     std::string line; 
     std::getline(numFile, line); 

     std::stringstream iss(line); 

     for (int col = 0; col < 10; col++){ 
    std::string num; 
    std::getline(iss, num, ' '); 

    std::stringstream converter(num); 
    converter >> threadArray[row][col]; 
     } 

    } 

    cout << "Original 2D Array" << endl << endl; 
    for (int i = 0; i < 10; i++){ 
     for (int j = 0; j < 10; j++){ 
    cout << threadArray[i][j] << " "; 
     } 
     cout << endl; 
    } 

    cout << endl; 

    } 

    srand (time(NULL)); 

    const int rowArray[3] = {1, 2, 5}; 

    int arrayIndex = rand() % 3; 
    int noOfRows = (rowArray[arrayIndex]); 
    end = noOfRows; 
    int noOfThreads = 10/noOfRows; 

    pthread_t threads[noOfThreads]; 

    arrayVar[2]; 

    cout << "2D Array Altered" << endl << endl; 

    for (int t = 0; t < noOfThreads; t++){ 
     arrayVar[0] = start; 
     arrayVar[1] = end; 
     rc = pthread_create(&threads[t], NULL, calc, NULL); 
     start = start + noOfRows; 
     end = end + noOfRows; 
     pthread_exit(NULL); 
    } 
} 

回答

2
for (int t = 0; t < noOfThreads; t++) 
{ 
    arrayVar[0] = start; 
    arrayVar[1] = end; 
    rc = pthread_create(&threads[t], NULL, calc, NULL); 
    start = start + noOfRows; 
    end = end + noOfRows; 
    // pthread_exit(NULL); <-- this EXITS the loop and main 
} 

注释掉上述pthread_exit和有第二个循环

for (int t = 0; t < noOfThreads; t++) 
{ 
    rc = pthread_join(threads[t], NULL); 
} 

pthread_exit(NULL); 
+0

我已经试过,但后来我得到一个错误消息说:从“的pthread_t *无效的转换{又名长的无符号int *}'改为'pthread_t {aka long unsigned int}' - 任何想法? – 6TTW014