When i try to run the program using 2 threads and a size of more than 4.5million it creates a segmentation fault. Anything below that number runs smoothly. In short very large numbers generate a segfault and i dont know why.I would like to know if the error has to do with the thread creation or the distribution of work to the threads. Some help will be appreciated. Below is the code.
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <ctime>
#include<algorithm>
/* define variables for the problem */
#define UPPER_LIM 10
#define LOWER_LIM 1
using namespace std;
/* function definitions */
int generate_random_number(unsigned int lower_limit, unsigned int upper_limit);
void merge_sort(vector<int>& array, int left, int right);
void merge(vector<int>& array, int left, int middle, int right);
void thread_merge_sort(vector<int>& array, int thread_id, int n, int p, int q);
bool isTest_array_is_in_order(vector<int>& array, int LENGTH);
int main(int argc, const char * argv[]) {
int NUM_THREADS = atoi (argv[1]);
int LENGTH = atoi(argv[2]);
int NUMBERS_PER_THREAD = LENGTH / NUM_THREADS;
int OFFSET = LENGTH % NUM_THREADS;
srand(time(0)) ;
std::vector<int> array;
array.reserve(LENGTH);
/* initialize array with random numbers */
for (int i = 0; i < LENGTH; i ++) {
array.push_back(generate_random_number(LOWER_LIM, UPPER_LIM));
}
/* begin timing */
auto start = std::chrono::high_resolution_clock::now();
const size_t nthreads = NUM_THREADS;//std::thread::hardware_concurrency();
{
// Pre loop
std::cout<<"parallel ("<<nthreads<<" threads):"<<std::endl;
std::vector<std::thread> workers;
for(std::size_t t = 0;t<nthreads;t++)
{
workers.push_back(thread(thread_merge_sort, ref(array), t, nthreads, NUMBERS_PER_THREAD, OFFSET));
}
for(thread& t: workers) { // await thread termination
t.join();
}
}
auto elapsed = std::chrono::high_resolution_clock::now() - start;
auto usec = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
// and print time
std::cout << "Spent " << usec << " executing "<<nthreads<<" in parallel "<< " array size "<<LENGTH<<std::endl;
/* end timing */
/* generate random numbers within the specified limit */
int generate_random_number(unsigned int lower_limit, unsigned int upper_limit) {
//srand(time( NULL ));
return lower_limit + (upper_limit - lower_limit) * ((double)rand() / RAND_MAX);
}
/** assigns work to each thread to perform merge sort */
void thread_merge_sort(vector<int> &arr, int thread_id, int NUM_THREADS, int NUMBERS_PER_THREAD, int OFFSET)
{
int left = thread_id * (NUMBERS_PER_THREAD);
int right = (thread_id + 1) * (NUMBERS_PER_THREAD) - 1;
if (thread_id == NUM_THREADS - 1) {
right += OFFSET;
}
int middle = left + (right - left) / 2;
if (left < right) {
merge_sort(arr, left, right);
merge_sort(arr, left + 1, right);
merge(arr, left, middle, right);
}
}
Aucun commentaire:
Enregistrer un commentaire