我正在处理一个类项目,并且遇到麻烦让我的线程完全通过文件读取。我可以让他们通过第一个或第二个字,然后他们停下来并且不输出任何东西。在我的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 ==&#39; Vowel&#34;
我的主要看起来像这样
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: Operating
Consonant Thread: Systems
Consonant Thread: Class
等,直到文件被读取为止
任何帮助都将受到赞赏,包括有关线程的资源或帮助我的代码的建议。提前谢谢!
答案 0 :(得分:0)
代码中的主要问题是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
位,这意味着Warning: main(): unterminated entity reference
线程无法输入您的元音输出代码。这是一个设计流程,我相信你会知道如何解决。
如果您需要进一步的精确度,请注意不要对我的回答发表评论。