Private data for threads (TSD-Thread-Specific Data)

Within a thread, thread private data can be accessed by individual functions, but it is blocked from other threads.

When using thread data, first create an associated key for each thread's data.Within each thread, this common key is used to refer to thread data, but in different threads, the data represented by this key is different.That is, once a key is created, all threads can access it, but each thread can fill in a different value for its own needs.This is equivalent to providing a global variable with the same name but different values, one key and multiple values.

There are four main functions that operate on thread private data:

  • pthread_key_create (create a key)
  • pthread_setspecific (set thread private data for a key)
  • pthread_getspecific (read thread private data from a key)
  • pthread_key_delete (delete a key)

The following code examples show how to create, use, and delete private data for threads:

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

//Declare key
pthread_key_t key;

//Thread 1 sets the thread's private data to 5, and then gets the data and prints it to the screen
void * thread1(void *arg)
{
    int tsd=5;
    printf("Thread %u is running\n",pthread_self());
    pthread_setspecific(key,(void*)tsd);
    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
}

//Thread 2 sets the thread's private data to 4, and then gets the data and prints it to the screen
void * thread2(void *arg)
{
    int tsd=4;
    printf("Thread %u is running\n",pthread_self());
    pthread_setspecific(key,(void*)tsd);
    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
}

int main(void)
{
    pthread_t thid1,thid2;
    printf("Main thread begins running\n");

	//Create this key
    pthread_key_create(&key,NULL);

	//Create 2 Subthreads
    pthread_create(&thid1,NULL,thread1,NULL);
    pthread_create(&thid2,NULL,thread2,NULL);

	//Waiting for 2 sub-threads to return
    int status1,status2;
    pthread_join(thid1,(void *)&status1);
    pthread_join(thid2,(void *)&status2);

	//Delete key
    pthread_key_delete(key);

    printf("main thread exit\n");
    return 0;
}

Run result:



These two threads separately use tsd as thread private data.From the point of view of the program running, the modifications to tsd made by the two threads do not interfere with each other.

Posted on Sun, 19 Jul 2020 11:17:08 -0400 by karimali831