【发布时间】:2023-04-08 21:47:01
【问题描述】:
函数void readFile1() 与void readfile2() 和void readfile3() 完全相同。我只是删除了它们以使其更易于阅读。一旦我解决了其中一个函数,我也可以将它添加到其余函数中。
我的问题是,每当我运行代码时,即使找到密码,线程也会继续运行,直到 3 个密码文件中的所有密码都被检查完。我正试图找到一种方法来阻止它。
我尝试添加一个信号量,以便它会向其他线程发出信号,表明其中一个线程在它正在查看的文本文件中找到了正确的密码,并告诉其他线程停止。但是当我尝试实现它时,我遇到了很多错误,我不确定这是解决我的问题的方法。所以,我对如何停止线程有点困惑!
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
using namespace std;
//Variables
string password = "";
bool password_not_found_t1 = false;
bool password_not_found_t2 = false;
bool password_not_found_t3 = false;
bool thread1_working = false;
bool thread2_working = false;
bool thread3_working = false;
//Functions
void readFile1(string file_name) {
thread1_working = true;
ifstream file(file_name);
if (file.is_open()) {
string line;
bool res = false;
while (getline(file, line)) {
system("cls");
if (thread1_working && thread2_working && thread3_working) {
printf("Thread 1 working... \nThread 2 working... \nThread 3 working... \n");
} else if (thread1_working && thread2_working) {
printf("Thread 1 working... \nThread 2 working... \n");
} else if (thread1_working && thread3_working) {
printf("Thread 1 working... \nThread 3 working... \n");
} else if (thread2_working && thread3_working) {
printf("Thread 2 working... \nThread 3 working... \n");
} else if (thread1_working) {
printf("Thread 1 working... \n");
} else if (thread2_working) {
printf("Thread 2 working... \n");
} else if (thread3_working) {
printf("Thread 3 working... \n");
}
string text_line = line.c_str();
if (text_line == password) {
printf("\n\nThe correct password was: %s \nFound on Thread 1\n\n", text_line.c_str());
res = true;
break;
}
this_thread::sleep_for(chrono::seconds(1));
}
if (!res) {
password_not_found_t1 = true;
}
file.close();
}
if (password_not_found_t1 && password_not_found_t2 && password_not_found_t3) {
system("cls");
printf("Password not found in database.\n\n");
}
thread1_working = false;
}
int main() {
ifstream correct_password("correct_password.txt");
if (correct_password.good()) {
getline(correct_password, password);
}
correct_password.close();
thread t1(readFile1, "password1.txt");
thread t2(readFile2, "password2.txt");
thread t3(readFile3, "password3.txt");
t1.join();
t2.join();
t3.join();
system("pause");
【问题讨论】:
-
如果
readFile2和readFile3看起来与此相同,则在访问由其中一个线程写入的那些共享变量之前绝对需要同步。实现这一点的简单方法是将它们设为atomic<bool>而不是bool,但考虑拥有更高级别的东西,例如每个线程的未来,您可以在main中进行协调(这消除了对全局变量的需要)。您也可以将password传递到线程中,而不是将其设为全局。 -
将其破解为正确的minimal reproducible example,您可能会找到您的错误。如果不是这样,使用 MRE 时,您就不必费力了,而且您更有可能得到一个好的、有针对性的答案。
-
如果找到密码,我是否可以更快地实施以使其停止查看文件?或者我是否需要在我考虑添加信号之前让它们同步?
-
同步必须在你开始使用线程时就内置,否则你将永远无法起步。
-
请注意,如果所有文件都在同一个磁盘上,您可能会发现您的程序并没有快多少,甚至可能更慢,因为线程为访问磁盘而争吵。跨度>
标签: c++ multithreading visual-c++