parallel-programming/3/threads/linux/thread3.cpp

147 lines
4.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//в этой программе описаны два метода: fork и thread. Метод thread работает как обычно. Метод fork не завершает выполнение программы, запустите его и подождите некоторое время (зависит от кол-ва потоков, у меня занимает
// около 10 секунд), после этого закройте терминал вручную. Извините, я понимаю, что это странно, но по-другому я не придумал
#include <iostream>
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <thread>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int fire(int i, int h, int l)
{
setlocale(LC_ALL, "Russian");
ofstream file2;
string path2 = "/home/mach_vl/Загрузки/500f/result" + to_string(i)+".txt"; //файл с промежуточным результатом для каждых 25 из 500 данных файлов
file2.open(path2);
for (int x = h; x<=l; x++)
{
ifstream file1;
string path1 = "/home/mach_vl/Загрузки/500f/" + to_string(x) + ".txt"; //500 данных файлов
file1.open(path1);
string ilya;
char sanya;
//cout<<x<<endl;
int lineCount = 0;
int wordCount = 0;
int symbolCount = 0;
while(getline(file1, ilya)) //читаем файл по строкам и считаем их кол-во
{
lineCount++;
}
file1.close();
file1.open(path1);
file1.seekg(0, file1.beg);
while(file1 >> ilya) //читаем файл по словам и считаем их кол-во
{
wordCount++;
}
file1.close();
file1.open(path1);
file1.seekg(0, file1.beg);
while(file1 >> sanya) //читаем файл по симолам и считаем их кол-во
{
symbolCount++;
}
//записываем результаты в файлы с промежуточными результатами
string vanya(to_string(x) + ") Lines: " + to_string(lineCount) + "; words: " + to_string(wordCount) + "; symbols: " + to_string(symbolCount));
file2 << vanya << endl;
file1.close();
}
file2.close();
//следующий фрагмент кода нужен только для fork. его описание есть внизу
/*if (i == 20)
{
ofstream result;
result.open("/home/mach_vl/Загрузки/500f/result.txt");
for (int i = 1; i <= 20; i++) {
ifstream jedi;
string path = "/home/mach_vl/Загрузки/500f/result" + to_string(i)+".txt";
jedi.open(path);
string rita;
while (getline(jedi, rita))
{
result << rita << endl;
}
jedi.close();
}
result.close();
}*/
//конец фрагмента для fork
return 0;
}
int main()
{
setlocale(LC_ALL, "Russian");
int x = 25; //500 файлов делим на 20 потоков (у вас может быть по-другому)
int h = 1;
int l = 25;
//начало thread
std::vector<std::thread> th;
for (int i = 1; i <= 20; i++) {
th.push_back(thread(fire, i, h, l)); //заполняем вектор thread'ами
h += x;
l += x;
}
for (auto& t : th) {
t.join(); //запускаем thread
}
ofstream result;
result.open("/home/mach_vl/Загрузки/500f/result.txt"); //открываем файл, в который запишем конечный результат
for (int i = 1; i <= 20; i++) {
ifstream jedi;
string path = "/home/mach_vl/Загрузки/500f/result" + to_string(i)+".txt"; //файлы с промежуточными результатами
jedi.open(path);
string rita;
while (getline(jedi, rita))
{
result << rita << endl; //переносим промежуточные результаты в конечный файл
}
jedi.close();
}
result.close();
//конец thread
//начало fork
/*for(int i = 1; i<=20; i++) //здесь нужно заменить 20 на ваше кол-во потоков
{
pid_t pid = fork();
if (pid==0)
{
fire(i, h, l); //вызов функции в дочернем процессе
}
wait(NULL);
h+=x;
l+=x;
}*/
//конец fork
return 0;
}