Domanda

I try to create simple app, which Write/read files on FTP server. I create a thread

    HANDLE hThread;
    unsigned threadID;
    hThread = (HANDLE)_beginthreadex( NULL, 0, &foo, NULL, 0,NULL );    
    CloseHandle( hThread );

A function foo() creates new internet session like this

      CInternetSession session(_T("Session"));

But after calling CInternetSession session(_T("Session")) thread ends

Is there a way to fix it?

È stato utile?

Soluzione

You need your thread function to wait on an event or enter a loop to prevent the function ending. When that function exits the thread will die.

For example you could use the the windows event API:

void foo(){
  // The Event exitSessionEvent must be declared somewhere where the controlling 
  // thread can access it. This might be a global event for example (in a namespace).
  // You must initialise it using CreateEvent.

  CInternetSession session(_T("Session"));
  // ... do some stuff ....
  WaitForSingleObject(exitSessionEvent, INFINITE);
  session.Close(); //Done so cleanup
}

Now the thread function will not exit until the event "exitSessionEvent" is set (by someone else).

You can also use a flag of some kind and have a while(flag) loop, but events are clearer ways to express yourself in multithreaded applications I think.

Also the thread that created your thread should not be the one to close it, unless it WAITS for it to end. It does not look like you are waiting for your new thread to finish before closing the handle for the thread. Again if using events then you could do this:

HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &foo, NULL, 0,NULL );  
WaitForSingleObject(hThread, INFINITE);  
CloseHandle( hThread );

That will wait for the thread to finish before closing the handle.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top