Mon 13 Jan 2014 08:38:41 PM UTC, comment #4:
You are right, there's an error in the code. using your example, it should be like this:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
static is_stop =0;
static pthread_key_t key_error_;
static pthread_once_t key_once_ = PTHREAD_ONCE_INIT;
static void create_keys_ (void)
{
int* error = NULL;
printf("create_keys_ thread %x\n", pthread_self());
pthread_key_create (&key_error_, free);
}
void error_code_init (int code)
{
int *error = NULL;
printf("error_code_init thread %x\n", pthread_self());
/* Initialize error code per thread. */
pthread_once (&key_once_, create_keys_);
error = (int *) pthread_getspecific (key_error_);
if (NULL == error)
{
error = (int *) malloc (sizeof (int));
pthread_setspecific (key_error_, error);
}
*error = code;
}
static void * th1_methd(void *arg)
{
printf("this is th1 thread %x\n", pthread_self());
sleep(10);
error_code_init(1);
is_stop++;
return NULL;
}
static void * th2_methd(void *arg)
{
printf("this is th2 thread %x\n", pthread_self());
sleep(2);
error_code_init(2);
is_stop++;
return NULL;
}
int main()
{
pthread_t th1;
pthread_t th2;
(void) pthread_create(&th1, NULL, th1_methd, 0);
(void) pthread_create(&th2, NULL, th2_methd, 0);
while(is_stop!= 2)
{
sleep(1);
}
printf("main exit\n");
return 0;
}
|