我在多线程程序中使用此代码:
class A{
public:
FILE *File;
bool ThFunc(){
if (CreateDataFile())
std::cout << "File was created\n";
else{
std::cout << "Can't create file\n";
return false;
}
//work with file
if (CloseDataFile()){
std::cout << "File was closed\n";
return true;
}
else{
std::cout << "Can't close file\n";
return false;
};
};
bool CreateDataFile(){
File = fopen ("binary_file.bin", "wb");
if (File!=NULL)
return true;
else
return false;
};
bool CloseDataFile(){
int t=fclose(File);
if (t!=0)
return false;
else{
//insert the file name in another thread
return true;
}
}
};
有时,在另一个线程(〜每10个文件)中有一个错误:“该文件被另一个程序(my.exe)使用”,但在控制台中我看到:“文件已关闭”。可能有什么不对?在使用ThFunc()并在之后解锁之前,互斥锁被锁定。