【发布时间】:2017-02-28 16:34:06
【问题描述】:
我正在处理一个班级项目,但在让我的线程完全读取文件时遇到了麻烦。我可以让他们读完前两个单词,然后他们停下来不输出任何东西。在我的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 == 'Vowel"
我的主要是这样的
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 等等,直到文件被读完
任何帮助都将不胜感激,包括有关线程的资源或帮助我的代码的建议。提前谢谢!
【问题讨论】:
-
文件是
std::fstream?你在哪里定义word?请提供Minimal, Complete, and Verifiable example -
如果不能使用同步原语,就不能使用并发。很不清楚你希望从这里使用多线程获得什么。
-
我添加了全局变量来帮助澄清这一点。 file 是一个 ifstream 全局变量。 Word 也是一个全局变量。转身就完成了。它们是全局的,因此线程可以访问它们。
-
为了帮助澄清问题,这里有一个代码应该做什么的例子。在 .txt 文件“phrase.txt”中,有一个简单的短语,如“Operating Systems Class Starts In The Evening” 输出应为 Vowel Thread: Operating Consonant Thread: Systems Consonant Thread: Class 等,直到文件被读取通过
-
@rhymeswithsilver 现在问题是正确的(afaik)。附带说明一下,使用跨线程的方式最好使用
std::atomic标头完成(考虑到您不能使用互斥锁)
标签: c++ multithreading fstream