Back to index

glibc  2.9
Functions | Variables
ex4.c File Reference
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

Go to the source code of this file.

Functions

static void str_alloc_key (void)
static void str_alloc_destroy_accu (void *accu)
static char * str_accumulate (const char *s)
static void * process (void *arg)
int main (int argc, char **argv)

Variables

static pthread_key_t str_key
static pthread_once_t str_alloc_key_once = PTHREAD_ONCE_INIT

Function Documentation

int main ( int  argc,
char **  argv 
)

Definition at line 102 of file ex4.c.

{
  char *res;
  pthread_t th1, th2;

  res = str_accumulate ("Result of ");
  pthread_create (&th1, NULL, process, (void *) "first");
  pthread_create (&th2, NULL, process, (void *) "second");
  res = str_accumulate ("initial thread");
  printf ("Thread %lx: \"%s\"\n", pthread_self (), res);
  pthread_join (th1, NULL);
  pthread_join (th2, NULL);
  return 0;
}

Here is the call graph for this function:

static void* process ( void *  arg) [static]

Definition at line 91 of file ex4.c.

{
  char *res;
  res = str_accumulate ("Result of ");
  res = str_accumulate ((char *) arg);
  res = str_accumulate (" thread");
  printf ("Thread %lx: \"%s\"\n", pthread_self (), res);
  return NULL;
}

Here is the call graph for this function:

Here is the caller graph for this function:

static char* str_accumulate ( const char *  s) [static]

Definition at line 45 of file ex4.c.

{
  char *accu;

  /* Make sure the key is allocated */
  pthread_once (&str_alloc_key_once, str_alloc_key);
  /* Get the thread-specific data associated with the key */
  accu = (char *) pthread_getspecific (str_key);
  /* It's initially NULL, meaning that we must allocate the buffer first. */
  if (accu == NULL)
    {
      accu = malloc (1024);
      if (accu == NULL)
       return NULL;
      accu[0] = 0;
      /* Store the buffer pointer in the thread-specific data. */
      pthread_setspecific (str_key, (void *) accu);
      printf ("Thread %lx: allocating buffer at %p\n", pthread_self (), accu);
    }
  /* Now we can use accu just as in the non thread-safe code. */
  strcat (accu, s);
  return accu;
}

Here is the call graph for this function:

Here is the caller graph for this function:

static void str_alloc_destroy_accu ( void *  accu) [static]

Definition at line 82 of file ex4.c.

{
  printf ("Thread %lx: freeing buffer at %p\n", pthread_self (), accu);
  free (accu);
}

Here is the call graph for this function:

Here is the caller graph for this function:

static void str_alloc_key ( void  ) [static]

Definition at line 72 of file ex4.c.

{
  pthread_key_create (&str_key, str_alloc_destroy_accu);
  printf ("Thread %lx: allocated key %d\n", pthread_self (), str_key);
}

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Definition at line 36 of file ex4.c.

Definition at line 33 of file ex4.c.