Pthread---Initialize && thread private data at a one-time

Source: Internet
Author: User
Tags function prototype posix

Initialization at a one-time

Sometimes we need to initialize only once for some POSIX variables, such as Line Cheng (which I'll talk about below). If we initialize the program more than once, there will be an error.

In traditional sequential programming, one-time initialization is often managed by using Boolean variables. Control variables are initialized to 0 statically, and any code that relies on initialization can test the variable. If the value of the variable is still 0, it can initialize and then set the variable to 1. Code that is checked later will skip initialization.

But in the design of multithreaded programming, things become more complicated. If multiple threads execute the initialization sequence code concurrently, 2 threads may find the control variable to be 0 and all are initialized, and the process should only be executed once.

If we need static initialization of a POSIX variable, the method to use is to control the initial words of the variable with a mutex. But sometimes we need to initialize the variable dynamically, and the pthread_once will be much more convenient.

Function prototype:

pthread_once_t Once_control=pthread_once_init;

int Pthread_once (pthread_once_t *once_control,void (*init_routine) (void));

Parameters:

Once_control Control variables

Init_routine initialization function

return value:

If you return 0 successfully, if the failure returns an error number.

A variable of type pthread_once_t is a control variable. Control variables must be statically initialized using the Pthread_once_init macro.

The Pthread_once function first checks the control variable to determine whether the initialization has been completed and simply returns if it is completed, otherwise, the pthread_once calls the initialization function, and the initialization is completed under the record. If the other thread calls Pthread_once at the start of a thread, the calling thread waits until the ready-made completion of the initial word returns.


Thread Private Data:

The following is a thread stored in the threads specific Data. What is the use of thread storage. What does he mean by that? As you all know, in multithreaded programs, all threads share variables in the program. Now there is a global variable that all threads can use to change its value. And if each thread wants to have it alone, it needs to be stored with threads. It appears to be a global variable that all threads can use, and its value is stored separately in each thread. This is the meaning of thread storage.

The following is a specific usage of the thread storage.

Create a variable of type pthread_key_t type.

Call Pthread_key_create () to create the variable. The function has two parameters, the first argument is the pthread_key_t variable declared above, and the second is a cleanup function that is invoked when the thread is freed from the threads store. The function pointer can be set to NULL so that the system will invoke the default cleanup function.

You can call Pthread_setspcific () when you need to store special values in a thread. The function has two parameters, the first is the pthread_key_t variable declared earlier, and the second is the void* variable, so that you can store any type of value.

If you need to remove the stored value, call Pthread_getspecific (). The function's argument is the previously mentioned pthread_key_t variable, which returns the value of the void * type.

Here is the prototype of the function mentioned earlier:

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

void *pthread_getspecific (pthread_key_t key);

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


Examples are as follows:

* * @FileName: ONCE.C * @Author: WZJ * @Brief: * 1. Verify pthread_once Example * 2. Verifying the role of pthread_key_t History: * * * * @Date: June 03, 2012 13:19:15 * */#include <stdio.h> #include <pthread.h> #inclu

De <stdlib.h>//thread storage variables for global variable static pthread_key_t pid_key within a thread;
pthread_once_t once = Pthread_once_init;
	Pthread_once callback function, commonly used for one-time initialization of void Once_run (void) {int ret = 0;
	
	static int times = 1;	
	ret = Pthread_key_create (&pid_key, NULL);
	if (ret = 0) {printf ("Private key create success, by%u\n", pthread_self ());
	printf ("The%d Time run\n", times);
times++;

	} void* Child (void* Arg) {pthread_t tid = pthread_self ();
	printf ("Thread%u is run!\n", TID);
	Pthread_once (&once, Once_run);

	Set private value Pthread_setspecific (Pid_key, &tid);	
		while (1) {printf ("child:%d, Private key:%d\n", Pthread_self (), (int) pthread_getspecific (pid_key));
	Sleep (1);

	printf ("Thread%u is quit!\n", TID);
return 0; } INT Main () {pthread_t tid1, Tid2;
	Pthread_create (&AMP;TID1, NULL, child, NULL);
	
	Pthread_create (&AMP;TID2, NULL, child, NULL);
	Pthread_join (TID1, NULL);

	Pthread_join (Tid2, NULL);
	printf ("All exit!\n");
return 0; }








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.