<li********@hot mail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
: As i konw, the only way to to terminate a thread started by
: _beginthread() is to user _endthread() (or return) inside the thread.
:
: now i started a thread(TodoThre ad), and created a listenning socket
: inside the thread.
: I want to destroy the socket and kill the thread at anytime if there is
: no client connect to it. How?
You cannot safely and cleanly terminate a thread from the outside.
As C++ code, your thread's program will most likely be allocating
resources (e.g. heap-allocated memory from std::string, etc).
While some API's allow you to terminate a thread (e.g. with
cancelthread or TerminateThread ), they cannot ensure that these
resources are freed.
[some platforms may allow you to throw an exception into the
context of another thread, but that's also messy and hard
if at all possible to get right]
So what should you do instead?
- Use a child process instead of a thread: a modern OS
allows you to kill/terminate a process while ensuring
that its resources are properly released.
- Send some kind of signal to the thread asking it to
exit (e.g. if the thread is waiting on a semaphore,
set an exit request flag and signal that semaphore).
You then need to wait for the thread to exit cleanly.
Cheers,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <>
http://www.brainbench.com