PDA

View Full Version : [win32] CloseHandle su un thread


tomminno
12-09-2007, 14:10
Qual è il metodo migliore per eseguire la CloseHandle su un thread terminato?

Mi spiego meglio, ho una classe che lancia uno o più thread, chiaramente non voglio che questo thread sia bloccante quindi non posso scrivere qualcosa come:

thread.Start();
...
Thread::Start()
{
hThread = CreateThread(...);
WaitForSingleObject(...);
CloseHandle(hThread);
}

Se il thread termina per un comando esterno un metodo Stop della classe wrapper si occupa di eseguire la CloseHandle. Ma se il thread termina naturalmente, non c'è modo di segnalare questo evento a nessuno, perchè per fare questo avrei bisogno di un altro thread che sta in attesa di questo evento.
L'handle rimane quindi aperto fino a che la l'oggetto thread non viene distrutto. C'è modo di riuscire a chiuderlo prima?

andbin
12-09-2007, 14:27
La documentazione dice:

CloseHandle invalidates the specified object handle, decrements the object's handle count, and performs object retention checks. After the last handle to an object is closed, the object is removed from the system.

Closing a thread handle does not terminate the associated thread. To remove a thread object, you must terminate the thread, then close all handles to the thread.

Quindi sarei portato a pensare che se chiudi subito l'handle appena dopo aver creato/avviato il thread non ci sono problemi.

tomminno
12-09-2007, 18:21
La documentazione dice:

CloseHandle invalidates the specified object handle, decrements the object's handle count, and performs object retention checks. After the last handle to an object is closed, the object is removed from the system.

Closing a thread handle does not terminate the associated thread. To remove a thread object, you must terminate the thread, then close all handles to the thread.

Quindi sarei portato a pensare che se chiudi subito l'handle appena dopo aver creato/avviato il thread non ci sono problemi.

E' quel "then close all handles".
Io generalmente, in questi casi chiudo l'handle subito prima del return della callback, ma mi è sempre rimasto il dubbio che non fosse propriamente corretto, in quanto il thread termina solo dopo il return.