I have a function std::threadthat calls fopento load a large file into an array:
void loadfile(char *fname, char *fbuffer, long fsize)
{
FILE *fp = fopen(fname, "rb");
fread(fbuffer, 1, fsize, fp);
flose(fp);
}
This is called:
std::thread loader(loadfile, fname, fbuffer, fsize);
loader.detach();
At some point, something in my program wants to stop reading this file and request another file. The problem is that by the time the pointer is deleted, the fbufferthread loaderis still continuing, and I get a race condition that throws an exception.
How can I kill this thread? My idea was to test for existence fbufferand possibly split it freadinto small pieces:
void loadfile(char *fname, char *fbuffer, long fsize)
{
FILE *fp = fopen(fname, "rb");
long ch = 0;
while (ch += 256 < fsize)
{
if (fbuffer == NULL) return;
fread(fbuffer + ch, 1, 256, fp);
}
fclose(fp);
}
Will this slow down the reading of the file? Do you have an idea?
source
share