65 lines
1.5 KiB
C++
65 lines
1.5 KiB
C++
#include <iostream>
|
|
#include <thread>
|
|
#include <random>
|
|
#include <mutex>
|
|
#include <fstream>
|
|
|
|
std::mutex mtx;
|
|
int random_numbers[3] = {0, 0, 0};
|
|
int random_choice = 0;
|
|
|
|
void generateRandomNumber(int index, int min, int max) {
|
|
try {
|
|
std::random_device rd;
|
|
std::mt19937 gen(rd());
|
|
std::uniform_int_distribution<> dis(min, max);
|
|
|
|
int number = dis(gen);
|
|
|
|
std::lock_guard<std::mutex> lock(mtx);
|
|
if (index >= 0 && index < 3) {
|
|
random_numbers[index] = number;
|
|
} else if (index == 3) {
|
|
random_choice = number;
|
|
}
|
|
|
|
} catch (const std::exception& e) {
|
|
// Handle exception if necessary
|
|
}
|
|
}
|
|
|
|
void saveRandomNumberToFile() {
|
|
try {
|
|
std::lock_guard<std::mutex> lock(mtx);
|
|
std::ofstream outfile("random_number.txt");
|
|
if (outfile.is_open()) {
|
|
outfile << random_numbers[random_choice - 1];
|
|
outfile.close();
|
|
}
|
|
} catch (const std::exception& e) {
|
|
// Handle exception if necessary
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
try {
|
|
std::thread threads[4];
|
|
for (int i = 0; i < 3; ++i) {
|
|
threads[i] = std::thread(generateRandomNumber, i, 1, 100);
|
|
}
|
|
threads[3] = std::thread(generateRandomNumber, 3, 1, 3);
|
|
|
|
for (int i = 0; i < 4; ++i) {
|
|
threads[i].join();
|
|
}
|
|
|
|
saveRandomNumberToFile();
|
|
|
|
} catch (const std::exception& e) {
|
|
// Handle exception if necessary
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|