I encountered a problem when I was trying to open separate txt files in multi-threads, i.e., each thread opens a txt file and read content, the code is as follows.
#include<stdlib.h>
#include<windows.h>
#include<process.h>
DWORD WINAPI lookup1(LPVOID lpParamter){
char x[10];
int y;
FILE* fin1 = fopen("D:\\1.txt", "r");
fscanf(fin1, "%s %d", x, &y);
printf("%s %d", x, y);
fclose(fin1);
return 0;
}
DWORD WINAPI lookup2(LPVOID lpParamter){
char x[10];
int y;
FILE* fin2 = fopen("D:\\2.txt", "r");
fscanf(fin2, "%s %d", x, &y);
printf("%s %d", x, y);
fclose(fin2);
return 0;
}
int main(){
CreateThread(NULL, 0, lookup1, NULL, 0, NULL);
CreateThread(NULL, 0, lookup2, NULL, 0, NULL);
return 0;
}
I think this is a very simple program, each thread opens a separate file and reads from it. There is no file sharing or other complex situations involved, but I find that each thread does not successfully open the file, the rest of the code after fopen is skipped without any information prompted. When I debug this program, it even got stuck at the fopen or fscanf statement, and never recovered (Windows OS crashed). I don’t know why, please help me, thanks!!!
Edit: by changing the main function to the following code, the question is addressed, thank you very much!
int main(){
HANDLE hThread1 = CreateThread(NULL, 0, lookup1, NULL, 0, NULL);
HANDLE hThread2 = CreateThread(NULL, 0, lookup2, NULL, 0, NULL);
WaitForSingleObject(hThread1, INFINITE);
WaitForSingleObject(hThread2, INFINITE);
CloseHandle(hThread1);
CloseHandle(hThread2);
return 0;
}
The app spawns two threads and then exits before the threads have a chance to do anything.
CreateThreadreturns aHANDLE. Those HANDLEs are waitable objects that can be passed toWaitForSingleObject.