I have some code, roughly:
pthread_create(thread_timeout, NULL, handleTimeOut, NULL);
void handleTimeOut()
{开发者_JS百科
/*...*/
pthread_cancel(thread_timeout);
/*...*/
}
But as I noticed by pthread's manual the cancellation must be used by another threads. I have tried to use pthread_exit() function instead, but this thread hangs on again...
How must the tread termination be handled correctly? Will it be terminated successfully if the function handleTimeOut() just ends without special pthread functions?
Killing a thread without its cooperation is a recipe for problems. The right solution will be one that allows an external thread to request the thread to clean up and terminate, and has the thread periodically example this state and when it's been requested, it follows through with the request. Such a request can be done through anything that all threads can share.
If a thread wants to finish, it can either call pthread_exit()
or it can return from the initial thread function. These are equivalent.
I don't see any reason why a thread couldn't call pthread_cancel()
on itself, but this would be highly unusual.
精彩评论