我在使用線程函數查找二維數組中的最大條目時遇到了一些問題。我已經粘在屏幕上好幾個小時了,我可以用一些幫助。線程在C++中,查找二維數組中的最大條目
下面是代碼:
#include <iostream>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <random>
#include <ctime>
#include <future>
#include <thread>
using namespace std;
// A vanilla random number generator
double genRandNum(double min, double max){
return min + (rand()/(RAND_MAX/(max - min)));
}
double get_wallTime() {
struct timeval tp;
gettimeofday(&tp, NULL);
return (double) (tp.tv_sec + tp.tv_usec/1000000.0);
}
void getLargest(double** anArray, double largestEntry, int dimLower, int dimUpper, int dim) {
for (int i = dimLower; i < dimUpper; i++) {
for (int j = 0; j < dim; j++) {
if (anArray[i][j] > largestEntry) {
largestEntry = anArray[i][j];
}
}
}
}
// Main routine
int main(){
// Seed the random number generator
srand(time(NULL));
// 2D array dimension
int dim = 30000;
// Specify max values
double max = (double) (dim * dim * dim);
double min = (double) (dim * dim * dim * -1.0);
double t1 = get_wallTime();
// Create a 2D array
double **myArray = new double*[dim];
for (int i=0; i<dim; i++){
myArray[i] = new double[dim];
for (int j=0; j<dim; j++){
// generate random number
myArray[i][j] = genRandNum(min, max);
}
}
double largestEntry = 0.0;
double largestEntry2 = 0.0;
double largestEntry3 = 0.0;
double largestEntry4 = 0.0;
double largestEntry5 = 0.0;
int portion = dim/5;
std::future<void> thread1 = std::async (std::launch::async, getLargest, myArray, largestEntry, 0, portion, dim);
std::future<void> thread2 = std::async (std::launch::async, getLargest, myArray, largestEntry2, portion, (portion * 2), dim);
std::future<void> thread3 = std::async (std::launch::async, getLargest, myArray, largestEntry3, (portion * 2), (portion * 3), dim);
std::future<void> thread4 = std::async (std::launch::async, getLargest, myArray, largestEntry4, (portion * 3), (portion * 4), dim);
std::future<void> thread5 = std::async (std::launch::async, getLargest, myArray, largestEntry5, (portion *4), dim, dim);
thread1.get();
thread2.get();
thread3.get();
thread4.get();
thread5.get();
if (largestEntry2 > largestEntry) {
largestEntry = largestEntry2;
}
if (largestEntry3 > largestEntry) {
largestEntry = largestEntry3;
}
if (largestEntry4 > largestEntry) {
largestEntry = largestEntry4;
}
if (largestEntry5 > largestEntry) {
largestEntry = largestEntry5;
}
double t2 = get_wallTime();
double t3 = t2 - t1;
cout << " The largest entry is " << largestEntry << endl;
cout << "runtime : " << t3 << "\n";
}
我相信我正確設置了一切,但我只是學會了如何使用異步,所以我敢肯定的東西是不正確。運行時,我得到的最大輸入是零,這是錯誤的,我得到的運行時間比我預期的要長得多。
這裏是輸出:
The largest entry is 0
runtime : 13.8261
我覺得我傳遞largestEntry
到螺紋功能不正確,但我不知道如何解決它。線程函數getLargest
應該找到它提供的數組中最大的條目,並且當我創建線程時,我將它們中的每一個都分配給數組的一部分。
任何人可以提供任何意見將不勝感激。
這是[使用線程函數在二維數組中找到最大條目]的後續步驟(http://stackoverflow.com/questions/33535657/finding-largest-entry-in-2d-array-with-threaded-function) OP沒有解決那裏提到的所有問題。 – 1201ProgramAlarm