У меня есть набор пользователей и 2 потока (1 чтение, 1 запись), и с ними мне нужно переводить строку за строкой из одного текстового файла в другой и добавлять блокировки. Моя проблема заключается в том, что output.txt остается пустым, и данные передаются, и мои функции передаются следующим образом:
void MessagesSender::signnin(std::string username)
{
auto checkIffound = _user.find(username);
if ((checkIffound != _user.end()))
{
std::cout << username << " found in the user list" << std::endl;
}
else
{
std::lock_guard<std::mutex> user(m_user);
_user.insert(username);
}
}
void MessagesSender::writetoAlluser()
{
while (true)
{
std::ofstream output;
output.open("output.txt");
std::string tempMessage;
std::unique_lock<std::mutex> locker(m_message);
cond.wait(locker);
while (!_message.empty())
{
tempMessage = _message.front();
_message.pop();
std::lock_guard<std::mutex> user(m_user);
for (auto name : _user)
{
output << name << " : " << tempMessage << std::endl;
}
output.close();
}
locker.unlock();
}
}
void MessagesSender::readFromdata()
{
while(true)
{
std::ifstream data;
data.open("data.txt");
std::string buffer;
bool toEmpty = false;
std::unique_lock<std::mutex> locker(m_message, std::defer_lock);
if (data.is_open())
{
while (std::getline(data, buffer))
{
_message.push(buffer);
cond.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
data.close();
toEmpty = true;
}
if (toEmpty)
{
std::ofstream emptyFile;
emptyFile.open("data.txt", std::ofstream::out | std::ofstream::trunc);
emptyFile.close();
}
}
}
в основном. cpp
std::thread thread_read(read, std::ref(messagelist));
std::thread thread_write(write, std::ref(messagelist));
thread_read.detach();
thread_write.detach();
void read(MessagesSender &message)
{
message.readFromdata();
}
void write(MessagesSender &message)
{
message.writetoAlluser();
}
Мне нужно скопировать информация из data.txt в output.txt примерно так: name: «У меня проблема», вы можете мне помочь, если я ошибаюсь?