Answer the question
In order to leave comments, you need to log in
Link with an anchor in Russian and translation into English in the title attribute: are there any negative consequences?
I would like to hear if there are any negative consequences of using a link of this kind:
<a href="#" title="Marvel Universe">Вселенная Марвел</a>
Answer the question
In order to leave comments, you need to log in
Does this solution reduce link weight?
At a minimum, you pass the same input stream to all threads. There is a place to be not only a race, but generally a mess with access. The thread then locks the mutex while continuing ALL of its work. Your variant with the same success could work in one flow, tk. until a thread finishes reading, others will wait on the mutex. Block only on vector access.
Alternatively, code like this:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <deque>
#include <map>
#include <thread>
#include <mutex>
std::mutex lock;
void pipeline(const std::string&, std::vector<std::string>&);
std::string files[4] =
{
"file1.txt",
"file2.txt",
"file3.txt",
"file4.txt"
};
int main()
{
std::string string;
std::vector<std::string> str;
std::map<std::string, std::size_t> freq;
std::deque<std::thread> pool;
std::ofstream out("out.txt");
for (std::size_t i = 0; i < 3; i++)
{
pool.push_back(std::thread(pipeline, std::ref(files[i]), std::ref(str)));
}
while (pool.size())
{
pool.front().join();
pool.pop_front();
}
std::cout << str.size();
return 0;
}
void pipeline(const std::string &infile, std::vector<std::string> &str)
{
std::ifstream in(infile.c_str());
while (!in.eof())
{
std::string temp;
std::getline(in, temp);
{
std::unique_lock<std::mutex> guard(lock);
str.push_back(temp);
}
}
}
Here is the corrected version.
You passed one in to all of them and got into a race/deadlock.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <deque>
#include <map>
#include <thread>
#include <mutex>
std::mutex mutex;
std::string files[4] =
{
"file1.txt",
"file2.txt",
"file3.txt",
"file4.txt"
};
void pipeline(std::string &in, std::vector<std::string> &str)
{
std::lock_guard<std::mutex> lock(mutex);
std::ifstream file;
file.open(in);
while (!file.eof())
{
std::string temp;
std::getline(file, temp);
str.push_back(temp);
}
std::cout << in << " finished" << std::endl;
file.close();
}
int main()
{
std::string string;
std::vector<std::string> str;
std::map<std::string, std::size_t> freq;
std::deque<std::thread> pool;
std::ofstream out("out.txt");
for (std::size_t i = 0; i < 4; i++)
{
pool.push_back(std::thread(pipeline, std::ref(files[i]), std::ref(str)));
}
while (pool.size())
{
pool.front().join();
pool.pop_front();
}
out << str.size();
std::cout << str.size();
std::cin.get();
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question