Second problem is, because I have to use Sleep() in the file read loop, reading a 1 GB file takes more than 20 minutes.
I don't think sleep is needed.
Third problem is, whenever I put delete MyThread, my application always crashes. Any idea?
You need to set m_bAutoDelete to false and make sure the thread isn't running. I do
Code:
CWinThread* thread = AfxBeginThread(run, 0, THREAD_PRIORITY_NORMAL,
0, CREATE_SUSPENDED);
thread->m_bAutoDelete = false;
thread->ResumeThread();
The reason I first create the thread suspended is that the thread could conceivably complete before m_bAutoDelete is asigned. This way the thread is suspended when the m_bAutoDelete is assigned. The Website link I gave to you before goes into more depth. When I make sure to wait for the thread to exit. I do
Code:
WaitForSingleObject(readWorkerThread_->m_hThread, INFINITE);
delete readWorkerThread_;
readWorkerThread_ = 0;
I know when this code is run the thread is about to exit because this code is executed when the view receives UWM_FINISHED_READ(which is posted to the view when the thread is about to exit). Before this code is executed, the static stop variable is set inside the thread so that the thread proc will eventually exit.
The thread callback itself might look something like
Code:
UINT ReadWorker::run(LPVOID paramPtr)
{
int lineno = 0;
ReadWorker::waitForInitializeProgressDialog();
std::ifstream in(filename_.c_str());
while(!stop_ && !in.eof())
{
std::string line;
std::getline(in, line);
lineno++;
if (in)
{
ProgressInfo* info = new ProgressInfo(lineno, line);
WPARAM wp = reinterpret_cast<WPARAM>(info);
PostMessage(view_, UWM_PROGRESS_UPDATE, wp, 0);
Sleep(1000);
}
}
bool isCancelation = stop_;
ReadFinishInfo* finfo = new ReadFinishInfo(isCancelation);
WPARAM wpInfo = reinterpret_cast<WPARAM>(finfo);
PostMessage(view_, UWM_FINISHED_READ, wpInfo, 0);
return 0;
}
The stop_ variable is declared volatile because it is changed and read from two different threads. The windows that receive the messages are responsible for deleting their parameters.