gpt4 book ai didi

c++ - 代码不会提前通过条件变量的等待函数

转载 作者:行者123 更新时间:2023-11-30 03:53:02 25 4
gpt4 key购买 nike

因此,我一直试图更好地了解条件变量的工作原理,并且编写了以下代码来尝试从同一文本文件实现读取和写入:

    #include <iostream>
#include <fstream>
#include <cstdlib>
#include <condition_variable>
#include <mutex>
#include <thread>

using namespace std;

mutex mtx;
condition_variable conditionVariable;
ifstream readFile;
ofstream writeFile;
bool doneReading=false;
bool doneWriting=false;

void readFromFile()
{
string line;

readFile.open("./testFile.txt");

if(readFile.is_open())
{
cout << "Successfully opened file!" << "\n";
}
else
{
cout << "Failed to open file..." << "\n";
}

cout << "The file contents are:" << "\n";
while(getline(readFile,line))
{
unique_lock<mutex> lock(mtx);

conditionVariable.wait(lock, [] () {return doneWriting;});

cout << line << "\n";

doneReading=true;

lock.unlock();

conditionVariable.notify_one();
}
readFile.close();
}

void writeToFile()
{
string input;

writeFile.open("./testFile.txt");

cout << "Enter something you want to write to the text file:" << "\n";
cin >> input;
cout << "Going to write " << input << " to the file" << "\n";

if(writeFile.is_open())
{
cout << "Successfully opened file!" << "\n";

unique_lock<mutex> lock2(mtx);

/////////PROGRAM WON'T ADVANCE PAST THIS LINE/////////////
conditionVariable.wait(lock2, [] () {return doneReading;});

cout << "After calling the wait function for the condition variable" << "\n";

writeFile << input;

doneWriting=true;

lock2.unlock();

conditionVariable.notify_one();

writeFile.close();
}
else
{
cout << "Failed to open file..." << "\n";
}
}


int main()
{

int i;
for(i=0;i<10;i++)
{
thread t1(readFromFile);
thread t2(writeToFile);
t1.join();
t2.join();
}
}

并且,我在以下 example 之后模拟了我对 bool 变量的使用从cppreference.com(向下滚动到底部以查看示例代码)。但是,它与我传递给等待函数的谓词有关系,我不太确定它有什么问题。如果有人可以提供一些见解,那就太好了。谢谢!

最佳答案

初始状态是:

bool doneReading=false;
bool doneWriting=false;

readFromFile 对这些变量所做的第一件事就是等待 doneWriting 变为 true

conditionVariable.wait(lock, [] () {return doneWriting;});

writeFromFile 对这些变量所做的第一件事就是等待 doneReading 变为 true

conditionVariable.wait(lock2, [] () {return doneReading;}); 

这两个条件都不会成立。

请注意,cppreference 示例做了一些非常不同的事情:一个线程开始执行 cv.wait(lk, []{return ready;}); 而另一个线程开始执行 ready =真;

关于c++ - 代码不会提前通过条件变量的等待函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com