Linux system Programming-thread-private data

Source: Internet
Author: User

In multi-threaded programs, global variables are often used to realize data sharing among multiple functions. Because data spaces are shared, global variables are common to all threads.


The test code is as follows:

#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h>int key = 100; global variable void *helloworld_one (void *arg) {printf ("The message is%s\n", (char *) arg); key = 10;printf ("key=%d, the child ID is% lu\n ", Key, Pthread_self ()); return NULL;} void *helloworld_two (void *arg) {printf ("The message is%s\n", (char *) arg); sleep (1);p rintf ("key=%d, the child ID is%lu\n" , Key, Pthread_self ()); return NULL;} int main (int argc, char *argv[]) {pthread_t thread_id_one;pthread_t thread_id_two;//create thread pthread_create (&thread_id _one, NULL, Helloworld_one, "Helloworld_one");p thread_create (&thread_id_two, NULL, Helloworld_two, "helloworld_ \//wait for thread to end, recycle resource pthread_join (Thread_id_one, NULL);p thread_join (thread_id_two, null); return 0;}

The results of the operation are as follows:



As can be seen from the running result, one of the threads ' modifications to the global variable will affect access to another thread.


However, sometimes it is necessary to provide thread-private global variables in application design, which are only valid in threads, but can be accessed across multiple functions. For example, in a program where each thread may need to maintain a list, and the same function is used to manipulate the linked list, the simplest way is to use a thread-related data structure with the same name and different variable addresses. Such data structures can be maintained by Posix line libraries and become thread-private (thread-specific data, or TSD).


The required header files for the following interfaces:

#include <pthread.h>


1) Create thread-private data

int Pthread_key_create (pthread_key_t *key, Void (*destructor) (void*));

Function:

Create a private data variable (key) of type pthread_key_t.

Parameters:

< Span style= "COLOR: #ff0000" > key : Before allocating (malloc) thread private data, you need to create the key (key) associated with the thread private data, The function of this key is to gain access to the thread's private data.

destructor : Cleans up the function name (such as: Fun). This function is called automatically when the thread exits, if the thread private data address is not non-NULL. The function pointer can be set to NULL, so the system will invoke the default cleanup function.

callback letter The number is defined as follows:

void fun (void *arg)

{

//arg is a key value

}


return value:

Success: 0

Failure: not 0


Regardless of which thread calls Pthread_key_create (), the key that is created is accessible to all threads, but each thread can fill in the key with a different value according to its own needs, which is equivalent to providing a variable with a different value of the same name.


2) logoff thread private data

int Pthread_key_delete (pthread_key_t key);

Function:

Unregisters thread private data. This function does not check whether the thread private data (key) is currently being used by threads, and does not call the cleanup function destructor (), but simply frees the thread private data ( key) for use by the next call to Pthread_key_create ().

Parameters:

key: Private data to be unregistered.

return value:

Success: 0

Failure: not 0


3) Set the association of thread-private data

int pthread_setspecific (pthread_key_t key, const void *value);

Function:

Set the thread private data (key) and the value Association, and note that the value (not the indicated content) is associated with the key.

Parameters:

key: Thread-private data.

value: A pointer associated with key.

return value:

Success: 0

Failure: not 0


4) Read the values associated with the thread private data

void *pthread_getspecific (pthread_key_t key);

Function:

Reads the value associated with the thread private data (key).

Parameters:

key: Thread-private data.

return value:

Success: the value associated with the thread private data (key).

Failure: NULL


The sample code is as follows:

This is the test code for Pthread_key #include <stdio.h> #include <pthread.h> pthread_key_t key;//private data, global variable volume void echomsg (void *t) {printf ("[destructor] thread_id =%lu, param =%p\n", pthread_self (), t);} void *child1 (void *arg {int i = 10;pthread_t tid = pthread_self ();//thread number printf ("\nset key value%d in thread%lu\n", I, TID); pthread_setspeci FIC (key, &i); Set private data printf ("Thread one sleep 2 until thread finish\n\n"); Sleep (2); printf ("\nthread%lu returns%d, add is%p\n", Tid, * ((int *) pthread_getspecific (key)), Pthread_getspecific (key));  } void *child2 (void *arg) {int temp = 20;pthread_t tid = pthread_self (); Thread number printf ("\nset key value%d in thread%lu\n", temp, TID); Pthread_setspecific (key, &temp); Set Private Data sleep (1); printf ("Thread%lu returns%d, add is%p\n", TID, * (int *) pthread_getspecific (key)), Pthread_getspecific (key)); } int main (void) {pthread_t tid1,tid2; Pthread_key_create (&key, echomsg);//Create Pthread_create (&AMP;TID1, NULL, ChilD1, NULL); Pthread_create (&tid2, NULL, child2, NULL); Pthread_join (TID1, NULL);p thread_join (TID2, NULL);p thread_key_delete (key); Write-off return 0;  }

The results of the operation are as follows:



From the running results, each thread has no effect on its own private data operations. That is, although the key is of the same name and global, the memory space accessed is not the same.


For this tutorial sample code download please click here.


This article turns from:"Linux Advanced Programming"

Linux system Programming-thread-private data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.