Wednesday, June 06, 2007

pthread example

Set pthread joinable or detached status?

Usually, the default pthread attribution is in joinable status, and then we always encounter a case that multiple threads created when asynchronous. For example, main process created thread 1 and then wait for the thread1 to finish to join it back. But at the same time, the main process cannot create another thread any more.

And something notable is that we cannot just create pthreads of joinable without waiting to join them, because joining them in is like resource recycle mechanism when they are finished.

So why are the joinable threads so worthy? What i understand is that the process which created the joinable pthread needed to know the return status from the pthread it created. In that way, the joinable pthread is worthy to wati to join back.

On the contrary, not every pthread we must to wait. At this moment, we can create them as detached status, which means we just create and leave them away, no status returned from them. Actually, if we create pthread as detached status, we can create them infinitely without waiting to join them back, and we don't need to do that basically.

sample code below,


#include
#include

void *run(void *argv)
{
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  pthread_t thd;
  pthread_attr_t attr;
  int i=0, rc=0;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  for (i=0; 1; ++i) {
    if ( (rc=pthread_create(&thd, &attr, run, (void*)i))!=0 ) {
      printf("After %d pthread created(rc=%d)\n", i, rc);
      perror("pthread_create");
      return -1;
    }

#if 0
    if ( (rc=pthread_join(thd, NULL))!=0 ) {
      perror("pthread_join");
      return -1;
    }
#endif

    if ( i%100==0 ) {
      printf("%dth pthread created\n", i);
    }
  }

  pthread_attr_destroy(&attr);
  return 0;

}

Result:
After 382 pthreads created(errno:12)
pthread_create: Cannot allocate memory


#include
#include

void *run(void *argv)
{
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  pthread_t thd;
  pthread_attr_t attr;
  int i=0, rc=0;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

  for (i=0; 1; ++i) {
    if ( (rc=pthread_create(&thd, &attr, run, (void*)i))!=0 ) {
      printf("After %d pthread created(rc=%d)\n", i, rc);
      perror("pthread_create");
      return -1;
    }

    if ( i%100==0 ) {
      printf("%dth pthread created\n", i);
    }

  }

  pthread_attr_destroy(&attr);
  return 0;

}

Result:
2700th pthread created
2800th pthread created
2900th pthread created
3000th pthread created
3100th pthread created
After 3183 pthread created(rc=11)

pthread_create: Resource temporarily unavailable

No comments: