我熟悉C / Linux多线程,但这次我必须在Windows上使用C ++做一些工作,但我无法掌握它。在我的程序中,我有2个函数,它们不断尝试访问同一个文件来进行一些打印操作,会发生什么,其中一个从不起作用,这让我觉得函数永远不能打开文件,因为另一个可以随时写上它。如何实现线程以使其工作?代码大致如下:
std:mutex mut;
main(){
while(1){
//get mychar from user
print1(mychar, "my.txt");
print2();
}
}
print1(int i, char* file){
FILE *f = fopen(file, "a");
/*print operations
..
.*/
fclose(f);
return 0;
}
void print2(){
/*getting a string
...
Sleep(200);
getting another string
...*/
char getX[]; //fill buffers with the strings accordingly
char getY[]; //basically i want to know if the initial string has changed
if(*getX != *getY){
std::Lock_guard<std::mutex> guard(mut);
FILE *f = fopen("my.txt", "a");
fprintf(f, "%s ", getY);
fclose(f);
}
getX = NULL;
getY = NULL;
}
答案 0 :(得分:3)
第一个问题是你的互斥锁是在main中声明的。它们需要可以访问您的功能。如果您的程序中的所有相关内容都发生在这个文件中,那么使用全局声明的互斥锁完全没问题。
第二个问题是你没有正确地锁定任何一个线程。如果您要打开两个文件进行追加,那么最安全的做法是锁定打开并在关闭时解锁。您可以通过使用函数条目上的全局互斥锁初始化锁定保护来实现此目的:
std::mutex mut;
main(){
while(1){
//get mychar from user
print1(mychar, "my.txt");
print2();
}
}
print1(int i, char* file){
std::lock_guard<std::mutex> guard(mut);
FILE *f = fopen(file, "a");
/*print operations
..
.*/
fclose(f);
return 0;
}
void print2(){
/*getting a string
...
Sleep(200);
getting another string
...*/
char getX[]; //fill buffers with the strings accordingly
char getY[]; //basically i want to know if the initial string has changed
if(*getX != *getY){
std::lock_guard<std::mutex> guard(mut);
FILE *f = fopen("my.txt", "a");
fprintf(f, "%s ", getY);
fclose(f);
}
getX = NULL;
getY = NULL;
}
正如其他人所指出的,你甚至不在这里使用并发。它只是一个接一个的函数调用。如果您想使用线程,可以在while(1)
循环中执行此操作:
while(1){
std::thread thread1(print1, mychar, "my.text");
std::thread thread2(print2);
thread1.join();
thread2.join();
}
编辑:我已经编辑了print2
函数,只有在需要写入文件时才能打开文件。这使得并发性在应用程序结构中更加明智。