1 Thread-specific data
2 Thread local storage
准备中...
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
pthread_key_t key;
pthread_key_t key2;
struct test_struct {
int i;
float k;
}struct_data;
int temp;
void destroykey(void *td) {
pthread_setspecific (key, NULL);
free(td);
}
void destroykey2(void *temp) {
pthread_setspecific (key2, NULL);
free(temp);
}
int setspecificvar () {
int *temp = malloc(sizeof(int));
struct test_struct *td = malloc(sizeof(struct test_struct));
memset(td, 0, sizeof(struct test_struct));
memset(temp, 0, sizeof(int));
pthread_setspecific (key, td);
pthread_setspecific (key2, temp);
return 0;
}
int changedata (int i, float k, int tempvar) {
int *temp = pthread_getspecific(key2);
*temp = tempvar;
struct test_struct *td1 = pthread_getspecific(key);
td1->i = i;
td1->k = k;
return 0;
}
int printdata (int t) {
int *temp = pthread_getspecific(key2);
struct test_struct *td1 = pthread_getspecific(key);
printf ("The addres in child%d returned from pthread_getspecific(key):0x%p\n", t, (struct test_struct *)pthread_getspecific(key));
printf ("The value of members in structure bound to \"key\" in child%d:\nstruct_data.i:%d\nstruct_data.k: %f\n", t, td1->i, td1->k);
printf ("------------------------------------------------------\n");
printf ("The addres in child%d returned from pthread_getspecific(key2):0x%p\n", t, (int *)pthread_getspecific(key2));
printf ("The value of \"temp\" bound to \"key2\" in child%d:%d\n", t, *temp);
return 0;
}
void *child1 (void *arg) {
setspecificvar ();
changedata(10, 3.141500, 110);
printdata(1);
}
void *child2 (void *arg) {
setspecificvar ();
changedata(211, 2.141500, 211);
printdata(2);
changedata (222, 22.141500, 2222);
printdata (2);
}
int create_key () {
pthread_key_create (&key, destroykey);
pthread_key_create (&key2, destroykey2);
return 0;
}
int delete_key () {
pthread_key_delete (key);
pthread_key_delete (key2);
return 0;
}
int main (int argc, char *argv[]) {
pthread_t tid1, tid2;
create_key ();
pthread_create (&tid1, NULL, (void *)child1, NULL);
pthread_create (&tid2, NULL, (void *)child2, NULL);
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
delete_key ();
return 0;
}
参考:
http://stackoverflow.com/questions/14260668/how-to-use-thread-specific-data-correctly
http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzahw%2Frzahwe21rx.htm
http://cboard.cprogramming.com/c-programming/153492-thread-specific-data-not-work-fine-me-pthread.html