[Prev] [Contents] [Next]

pthread_self()--Get Pthread Handle

Syntax

#include <pthread.h>
pthread_t pthread_self(void);
Threadsafe: Yes
Signal Safe: Yes

The pthread_self() function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np() to return an integral identifier for the thread.

If your code requires the unique integer identifier for the calling thread often, or in a loop, the pthread_getthreadid_np() function can provide significant performance improvements over the combination of pthread_self(), and pthread_getunique_np() calls that provide equivalent behavior.

For example:

pthread_id_np_t   tid;
tid = pthread_getthreadid_np();
is significantly faster than these calls, but provides the same behavior.

pthread_id_np_t   tid;
pthread_t         self;
self = pthread_self();
pthread_getunique_np(&self, &tid);
As always, if you are calling any function too often, performance improvements can be gained by storing the results in a variable and or passing to other functions which require the results.

Parameters

None.

Authorities and Locks

None.

Return Value

pthread_t
pthread_self() returns the Pthread handle of the calling thread.

Error Conditions

None.

Related Information

Example

#include <pthread.h>
#include <pthread.h>
#include <stdio.h>
#include "check.h"

pthread_t   theThread;

void *threadfunc(void *parm)
{
 printf("Inside secondary thread\n");
  theThread = pthread_self();
  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t             thread;
  int                   rc=0;

  printf("Entering testcase\n");
  
  printf("Create thread using default attributes\n");
  rc = pthread_create(&thread, NULL, threadfunc, NULL);
  checkResults("pthread_create()\n", rc);

  /* sleep() isn't a very robust way to wait for the thread */
  sleep(5);

  printf("Check if the thread got its thread handle\n");
  if (!pthread_equal(thread, theThread)) {
     printf("Unexpected results on pthread_equal()!\n");
     exit(1);
  }
  printf("pthread_self() returned the thread handle\n");  
  printf("Main completed\n");
  return 0;
}
Output

Entering testcase
Create thread using default attributes
Inside secondary thread
Check if the thread got its thread handle
pthread_self() returned the thread handle
Main completed


[Prev] [Contents] [Next]
Copyright © 1998, IBM Corporation. All rights reserved.
Comments? Contact
rchthrds@us.ibm.com