I write a code in order to print all the number from a begin to end that the user writes. I want to do this with threading. For example the begin is 1 and the end is 100. I ask the users to enter a N number that is the number of threading that the program create. For example if he enters 10, the program will create 10 thread. The first thread will print primes number from 1 to 10. The second thread will print primes number from 10 to 20. The third from 20 to 30 and son on..
But I have a problem. In fact, my program prints many number in the file that are not primes number, and more than that often I have in the code the same number many times.
This is my code :
void writePrimesToFile(int begin, int end, ofstream& file)
{
for (int i = begin; i <= end; i++)
{
for (int j = begin; j < end / 2; j++)
{
if (i % j != 0)
{
file << i << endl;
}
}
}
}
void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N)
{
ofstream myfile(filePath);
clock_t startTimer, stopTimer;
startTimer = clock();
vector<thread> arr;
for (int i = 0; i < N; i++)
{
int start = begin;
int finish = N;
arr.emplace_back(writePrimesToFile, start, finish, ref(myfile));
start = finish;
finish += N;
}
for (auto& thread : arr)
{
thread.join();
}
stopTimer = clock();
cout << "The time that takes is: " << (double)(stopTimer - startTimer) / CLOCKS_PER_SEC << endl;
}
Code in the main:
callWritePrimesMultipleThreads(1, 100, "primes2.txt", 10);