[so] [tema 3] problema cu TSD

Tudor Golubenco so@cursuri.cs.pub.ro
Tue, 30 Nov 2004 23:02:58 +0200


In legatura cu initializarea indexului TSD  la o valoare nenula, am
intalnit o problema. Din ce am inteles eu, pthread_setspecific() modifica
indexul doar pentru threadul curent. Deci, daca apelam 
pthread_setspecific()
in constructorul librariei se va modifica indexul doar pentru threadul
principal iar in celelalte threaduri pthread_getspecific() va intoarce tot
NULL.

Am scris un program minimal din care am tras concluzia de mai sus. Il copiez
aici pentru cazul in care am gresit altceva sau am inteles prost indicatia
din enunt.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_key_t key;

void *thread_func(void *param)
{
  int ret;
 
  printf("%d\n", (int)pthread_getspecific(key));

  if ((ret = pthread_setspecific(key, (void*)1)) != 0)
    fprintf(stderr, "pthread_setspecific failed with errcode = %d", ret);

  printf("%d\n", (int)pthread_getspecific(key));
 

  return NULL;

}


int main()
{
  int ret;
  pthread_t t;

  if ((ret = pthread_key_create(&key, NULL)) != 0)
    {
      fprintf(stderr, "pthread_key_create failed with errcode = %d", ret);
      exit(-1);
    }
  if ((ret = pthread_setspecific(key, (void*)1)) != 0)
    {
      fprintf(stderr, "pthread_setspecific failed with errcode = %d", ret);
      exit(-1);
    }

  if ((ret = pthread_create(&t, NULL, &thread_func, NULL)) != 0)
    {
      fprintf(stderr, "pthread_create failed with errcode = %d", ret);
      exit(1);
    }
 
  if ((ret = pthread_join(t, NULL)) != 0)
    {
      fprintf(stderr, "pthread_join failed with errcode = %d", ret);
      exit(1);
    }

  return 0;
}

Programul afiseaza 0 si apoi 1.

Multumesc,
--Tudor


---------------------------------------------------------------
Posteaza gratuit anunturi de orice dimensiune si ai audienta de sute de mii, lunar.