jabk
jabk

Reputation: 1458

What happens to the pthread when it exits the function

Say I use pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*fun) (void *), void *arg) in a while loop, what happens to the thread(s) once it finishes function fun(), does it also fall in to the loop with the main thread if I call int pthread_detach(pthread_t thread) or does only the main thread stay in the loop?

Example:

pthread_t t[NTHREADS];

int i = -1;
while(1){

  //do something
  ++i;

  pthread_create(&t[i], NULL, fun, (void *)i);
  pthread_detach(t[i]);

  //main thread goes on, created one detaches when finished

}

What I want to do is a multi client server where each thread serves it's own client, there is NTHREADS and when certain thread finishes fun() or rather serving it's client, then the slot in t[] opens up and another thread can be created(other client can connect) if it was full before.

Upvotes: 0

Views: 1367

Answers (2)

nneonneo
nneonneo

Reputation: 179402

The specification says that returning from a thread function is equivalent to calling pthread_exit, with the thread function's return value becoming available to pthread_join (provided you didn't detach the thread).

Typically, this is implemented by having pthread_create create a thread that starts executing a fixed (libc) "thread entry function". This entry function calls your function, then calls pthread_exit (after any relevant cleanup is done).

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182753

A pthread returning from its start function is equivalent to that thread calling pthread_exit. If the thread is detached, it ceases to exist.

Upvotes: 1

Related Questions