3

I have some code, roughly:

pthread_create(thread_timeout, NULL, handleTimeOut, NULL);

void handleTimeOut()
{
  /*...*/
  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?

Mat
  • 202,337
  • 40
  • 393
  • 406
Rorschach
  • 31
  • 1
  • 2

2 Answers2

2

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.

mah
  • 39,056
  • 9
  • 76
  • 93
  • What functions should be used to terminate thread? cancel, exit, kill? – Rorschach Jun 22 '11 at 10:18
  • The point is that thread A should not use any function to _directly_ terminate thread B... instead, threads A and B need to be designed such that thread A can request that thread B terminate itself, and thread B will honor that request at the next convenient time. This allows thread B to perform a proper cleanup, releasing its resources and doing anything else it must do to perform a tidy termination. – mah Jun 22 '11 at 16:46
  • Perhaps I misunderstood, and you're asking how thread A terminates itself? If this is the case, as @caf stated, pthread_exit() is fine (unless its easier to just run off the end of your primary thread function). – mah Jun 22 '11 at 16:47
0

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.

caf
  • 233,326
  • 40
  • 323
  • 462