Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem writing into a file from another thread

Status
Not open for further replies.

SashaBuilder3

Programmer
Jan 13, 2002
131
CA
Hi everybody,

I am writing a program which should run in two threads. I created a global variable of FILE type. On start the main thread creates another thread. When click the Start button, the main thread opens the file, then activates the other thread (ResumeThread). This second thread should write into the file some text. However it doesn't. No error messages on compilation, just no records in the file while running.

To open the second thread I use the API CreateThread function. Here is a simplified version of the program.

Code:
//global vars:

HANDLE Thread;
FILE *myfile;



__fastcall Form1::Form1(TComponent* Owner)
  : TForm(Owner)
{
 DWORD Id;


 Thread = CreateThread(0,0,SecondThreadProcess,Form1->Handle, CREATE_SUSPENDED, &Id);

 if(!Thread)
 {
  ShowMessage("Error! Cannot create thread");
  Application->Terminate();
 }


DWORD WINAPI SecondThreadProcess( LPVOID lpParam )
 {
  char ch;

  for(i=0;i<100;i++)
   {
    ch=random(26);
    fprintf(myfile,&quot;char=%c&quot;,ch+65);
   } 

  return 0;
 }



void __fastcall Form1::BtnStartClick(TObject *Sender)
 {

  myfile=fopen(&quot;some.txt&quot;,&quot;w&quot;);

  ResumeThread(Thread);

  fclose(myfile);

 }



My guess is that some special steps should be taken for thread communication, but which ones?


Thanks,

Alexandre
 
I found the stupid thing I did: in the BtnStartClick function I close the file immediately after the thread resumes...



Sorry guys!

:-(

Alexandre
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top