Linux Multithreading Basics 2

Source: Internet
Author: User
Tags posix

6.

Name::

Pthread_detach

Function:

Causes the thread to enter a detached state.

Header file:

#include <pthread.h>

Function prototype:

int Pthread_detach (pthread_t tid);

Parameters:

return value:

Returns 0 if successful, otherwise the error number is returned.

By default, the terminating state of a thread is saved to call Pthread_join on that thread, and if the thread is already detached, the thread's underlying storage resource can be retracted as soon as it is terminated. When a thread is detached, it cannot wait for its terminating state with the Pthread_join function. A pthread_join call to a disconnected thread produces a failure, and the return Einval.pthread_detach call can be used to get the thread into a detached state.

7.

Name::

Pthread_cancel

Function:

Cancel other threads in the same process

Header file:

#include <pthread.h>

Function prototype:

int Pthread_cancel (pthread_t tid);

Parameters:

Tid thread ID

return value:

If 0 is returned successfully, the error number is returned.

By default, the Pthread_cancel function causes the thread identified by the TID to behave as if it had called the Pthread_exit function with the parameter pthead_canceled, but the thread can choose to ignore the cancellation mode and control the cancellation. Pthread_cancel does not wait for the thread to terminate, it only requests.

8.

Name::

Pthread_cancel_push/pthread_cancel_push_pop

Function:

Thread Cleanup handlers

Header file:

#include <pthread.h>

Function prototype:

void Pthread_cancel_push (void (*RTN) (void *), void *arg);

void Pthread_cancel_pop (int execute);

Parameters:

RTN Handler Entry Address

Arguments passed by Arg to the handler function

return value:

No

A thread can schedule a function to be called when it exits, a function called a thread cleanup handler, and a thread can establish multiple cleanup handlers. Handlers are recorded in the stack, meaning they are executed in the opposite order as they were registered.

Note that if a thread is terminated by returning from his startup routine, its handlers are not called. Also note that the cleanup handlers are called in the reverse order that they were installed.

#include <pthread.h>

#include <stdio.h>

void Cleanup (void *arg)

{

printf ("Cleanup:%s\n", (char *) arg);

}

void *thr_fn (void *arg)

{

printf ("Thread start\n");

Pthread_cleanup_push (cleanup, "thread first handler");

Pthread_cleanup_push (cleanup, "thread second handler");

printf ("Thread push complete\n");

Pthread_cleanup_pop (0);

Pthread_cleanup_pop (0);

}

int main ()

{

pthread_t Tid;

void *tret;

Pthread_creat (&TID,NULL,THR_FN, (void *) 1);

Pthread_join (Tid,&tret);

PTINRF ("Thread exit Code%d\n", (int) tret);

}

八、一次 initialization

Sometimes we need to initialize some POSIX variables only once, such as line Cheng (as I'll see below). If we initialize the program more than once, an error will occur.

In traditional sequential programming, one-time initialization is often managed by using Boolean variables. The control variable is statically initialized to 0, 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. The code that is checked later skips initialization.

But in multi-threaded programming, things become more complex. If multiple threads execute the initialization sequence code concurrently, 2 threads may find that the control variable is 0, and the initial session is implemented, and the process should be executed only once. The state of the initialization must be protected by a mutex.

If we need to initialize a POSIX variable statically, we can use a mutex to control the initial session of the variable. But sometimes we need to dynamically initialize the variable, and pthread_once is much more convenient.

9.

Name::

Pthread_once

Function:

Initialize once

Header file:

#include <pthread.h>

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 0 is returned successfully, the error number is returned if it fails.

Class

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 see if the initialization has been completed and simply returns if it is done, otherwise, pthread_once invokes the initialization function and records that initialization is complete. If another thread calls Pthread_once at the beginning of a thread, the calling thread waits until that ready-to-complete initial session is returned.

Here is an example of the program for this function:

#include <pthread.h>#include<stdio.h>pthread_once_t once=pthread_once_init;pthread_mutex_t Mutex;voidOnce_init_routine () {intstatus;//Status=pthread_mutex_init (&mutex,null);//if (status==0)printf"Init1 success!,my ID is%u\n", Pthread_self ());}void*child_thread (void*Arg) {printf ("I ' m child, My ID is%u\n", Pthread_self ()); Pthread_once (&once,once_init_routine);}intMainintargcChar*argv[])  {pthread_t child_thread_id; Pthread_create (&child_thread_id,null,child_thread,null); printf ("I ' m father,my ID is%u\n", Pthread_self ()); Pthread_once (&once,once_init_routine); Pthread_join (child_thread_id,null);}

The results of the program run as follows:

I ' m father,my ID is 3086874304

Init success!,my ID is 3086874304

I ' m child, My ID is 3086871472

As you can see from the above results, the initialization of the child function fails when the main function is initialized successfully.

Ix. Private data for threads

All threads within a process share the same address space, any variable declared as static or external, or a variable declared in the process heap, can be read and written by all threads of the process. How do you make a line program have its own private data?

POSIX provides a way to create a line Cheng.

10.

Name::

Pthread_key_create

Function:

To establish a thread private data key

Header file:

#include <pthread.h>

Function prototype:

int Pthread_key_create (Pthread_key *key,void (*destructor) (void *));

Parameters:

Key Private Data key

destructor Cleanup function

return value:

If 0 is returned successfully, the error number is returned if it fails.

The first parameter is a pointer to a key value, the second parameter indicates a destructor function (cleanup function), and if the argument is not NULL, the system calls this function to release the block of memory bound to the key when each thread ends. This function is often used in conjunction with the function pthread_once, in order for the key to be created only once. The function pthread_once declares an initialization function that executes the function the first time it is called pthread_once, and the subsequent invocation is ignored by it.

Here is an example of the program:

#include <pthread.h>

pthread_key_t Tsd_key;

pthread_once_t Key_once=pthread_once_init;

void Once_routine (void)

{

int status;

Status=pthread_key_create (&tsd_key,null);

if (status=0)

printf ("Key Create success! My ID is%u\n ", pthread_self ());

}

void *child_thread (void *arg)

{

printf ("I ' m child,my ID is%u\n", pthread_self ());

Pthread_once (&key_once,once_routine);

}

int main (int argc,char *argv[])

{

pthread_t child_thread_id;

Pthread_create (&child_thread_id,null,child_thread,null);

printf ("I ' m father,my ID is%u\n", pthread_self ());

Pthread_once (&key_once,once_routine);

}

The results of the program run as follows:

I ' m father,my ID is 3086231232

Key Create success! My ID is 3086231232

I ' m child,my ID is 2086228400

Linux Multithreading Basics 2

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.