Предполагается, что эта программа считывает из текстового файла и создает массив с размером первого числа в файле и заполняет его другим числом, которое будет нулем и единицами
, если значение равно нулю, это означает, что лампа неисправна, если она равна 1, лампа работает. Это назначение сделано для ознакомления с использованием потоков, поэтому рекурсия разбиения массива должна работать таким образом, чтобы к концу кода мы хотели узнать, сколько потоков было создано, и проследить нули, чтобы найти индекс для первого массива. и отображать индексы.
проблема, с которой я сталкиваюсь, заключается в том, что я не могу понять, как отследить эти значения, когда в моей функции запущены два потока, и при выполнении каждой рекурсии одновременно кто-нибудь может мне помочь с этим. Я хотел бы сохранить эти значения в векторе, поэтому функция вектора печати будет вызываться позже.
Спасибо.
// COEN346-Ass1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <string>
#include <thread>
#include <fstream>
#include <array>
#include <vector>
using namespace std;
static int TheCounter;
static vector<int> DefectiveBulbs;
void printVec(vector<int> vec) {
if (!DefectiveBulbs.empty()) {
cout << "Defective bulbs are : ";
for (int i = 0; i < vec.size(); i++) {
cout << vec.at(i) << " ";
}
cout << endl;
}
}
void FindDefective(int Arr[] , int size) {
bool check = false;
int scope = size;
for (int i = 0; i < scope; i++) {
if (Arr[i] == 0) {
check = true;
break;
}
}
if (check == false && TheCounter == 0) {
cout << "All bulbs are working properly" << endl;
}
if (scope == 1) {}
else if (check == true) {
int pivot = scope / 2;
int *LeftArr = new int[scope / 2];
int *RightArr = new int[scope / 2];
for (int i = 0; i < pivot; i++) {
LeftArr[i] = Arr[i];
RightArr[i] = Arr[scope / 2 + i];
}
thread t1(FindDefective,LeftArr , scope/2);
thread t2(FindDefective,RightArr,scope/2);
t1.join();
t2.join();
}
TheCounter++;
}
void BulbArr() {
ifstream infile;
string fileName;
label :
cout << "please enter file name (example: bulb.txt) :\n";
cin >> fileName;
infile.open(fileName);
if (!infile.fail()) {
int size;
infile >> size;
int *bulb = new int[size];
for (int i = 0; i < size; i++) {
infile >> bulb[i];
if (bulb[i] > 1 || bulb[i] < 0) {
cout << "input file has wrong values please try again.";
goto label;
}
}
thread t3(FindDefective, bulb , size);
t3.join();
}
}
int main()
{
BulbArr();
printVec(DefectiveBulbs);
cout << "The number of threads for this problem was : " << TheCounter << endl;
}