在线程函数 c++ 内读取文件流

Reading in a file stream inside a thread function c++

本文关键字:读取 文件 c++ 线程 函数      更新时间:2023-10-16

我正在处理一个类项目,在让我的线程完全读取文件时遇到了麻烦。我可以让他们通过前一两个单词,然后他们停止并且不输出任何东西。在我的main中,在我加入线程后,file.eof()返回 true。有没有人对为什么会发生这种情况或如何解决它有任何建议?

(该项目是使用交替线程从文件中的短语中"排序"元音和辅音;我不能使用互斥锁,这就是为什么有一个轮次变量)

void cons(){
cout << "Turn is " << turn << endl; //outputs "Turn is 0"
while (!file.eof()){
if (turn == false){
char c = word.at(0);
if (c != 'A' || c != 'E' || c != 'I'|| c != 'O'|| c != 'U'){
cout << "Consonant Thread: " << word << 'n';
file >> word;
}
turn = true;
}
this_thread::yield();
}
}
void vowel(){
while (!file.eof()){
if (turn == true){
char c = word.at(0);
if (c == 'A' || c == 'E' || c == 'I'|| c == 'O'|| c == 'U'){
cout << "Vowel Thread: " << word << 'n';
file >> word;
}
turn = false; //keeps track of thread turn to make sure the correct one is running
}
this_thread::yield();
}
}

上面是我的一个函数的例子,另一个是相似的,但使用 c == '元音'

我的主要看起来像这样

ifstream file;
string word;
bool turn = true; //true for vowel, false for cons
bool done = false;
int main(int argc, char *argv[]) {
{
file.open("phrase.txt");
file >> word;
if (file.eof()){
done = true;
}
std::thread vowelThread(vowel); //passing vow function 
std::thread consThread(cons); //passing cons function

cout << file.eof() << endl; //returns true
file.close();
vowelThread.join();
consThread.join();
cout << (file.eof()) << endl; //returns true
}

为了帮助澄清问题,下面是代码应执行的操作的示例。 在.txt文件"phrase.txt"中,有一个简单的短语,例如"Operating Systems Class Starts In The Evening"输出应Vowel Thread: OperatingConsonant Thread: SystemsConsonant Thread: Class等,等等,直到文件被读通

任何帮助将不胜感激,包括有关线程的资源或帮助我的代码的建议。提前谢谢你!

代码中的主要问题是main线程关闭文件,而另外两个线程在其上工作,设置eof位也就不足为奇了(线程无法再访问关闭的file)。 纠正此问题的正确方法是在线程返回后关闭file(即在每个线程从join()返回之后),但是您的程序仍然留下一个主要缺陷,即您如何设计cons函数和逻辑||使用,出于显而易见的原因,我已将其替换为&&

int main(int argc, char *argv[]) {
{
file.open("phrase.txt");
file >> word;
if (file.eof()){
done = true;
}
std::thread vowelThread(vowel); //passing vow function 
std::thread consThread(cons); //passing cons function

cout << file.eof() << endl; //returns true
//file.close(); <- closes file while your threads work on it, thus the eof bit is set
vowelThread.join();
consThread.join();
file.close();
cout << (file.eof()) << endl; //returns true
}

cons

void cons() {
cout << "Turn is " << turn << endl; //outputs "Turn is 0"
while (!file.eof()) {
if (turn == false) {
char c = word.at(0);
if (c != 'A' && c != 'E' && c != 'I' && c != 'O' && c != 'U') {
cout << "Consonant Thread: " << word << 'n';
file >> word;
}
turn = true;
}
//this_thread::yield();
}
}

附带说明一下,既然您已经看到了cons中的错误,您可能会理解为什么我坚持要求您提供每个函数,而不是要求我们从另一个函数中推断出一个函数。

还有最后一个问题(请注意,您的代码中有几个缺陷,为了保持主题,我没有解决这些缺陷):最后一个单词Evening没有输出,因为当cons打印The时,它会Evening加载到word中,并设置eof位,这意味着vowel线程无法输入元音输出代码。这是一个设计流程,我相信你会知道如何解决。

如果您需要进一步的精度,请注意犹豫是否要对我的回答发表评论。