LINUX multi-thread pthread learning Summary

Source: Internet
Author: User

Introduction

POSIX thread is short for pthread, and POSIX thread isPOSIXStandard thread. This standard defines the internal API creation and thread manipulation.

 

Function

The thread library implements the POSIX thread standard, usually known as pthreads. pthreads is the most commonly used POSIX systems such as Linux and UNIX, while Microsoft windowsimplementations exist at the same time. For example, the pthreads-w32 can support the pthread of MIDP

Pthreads defines a set of CProgramLanguage type, function, and constant. It is implemented using the pthread. h header file and a thread library.

 

Data Type

Pthread_t: thread handle

Pthread_attr_t: thread attribute

Thread-manipulation function (omitted for the sake of Introduction)

Pthread_create (): Creates a thread.

Pthread_exit (): Terminate the current thread

Pthread_cancel (): interrupts the running of another thread.

Pthread_join (): blocks the current thread until another thread stops running.

Pthread_attr_init (): attributes of the initialization thread

Pthread_attr_setdetachstate (): sets the off-state attribute (determines whether the thread can be combined upon termination)

Pthread_attr_getdetachstate (): gets the out-of-state attribute.

Pthread_attr_destroy (): deletes attributes of a thread.

Pthread_kill (): sends a signal to the thread

 

Synchronous Functions

Used for mutex and condition Variables

Pthread_mutex_init () initializes the mutex lock.

Pthread_mutex_destroy () delete a mutex lock

Pthread_mutex_lock (): exclusive lock (blocking operation)

Pthread_mutex_trylock (): attempts to occupy the mutex lock (non-blocking operation ). This lock will be occupied when the mutex lock is idle; otherwise, it will be returned immediately.

Pthread_mutex_unlock (): releases the mutex lock.

Pthread_cond_init (): initialization condition variable

Pthread_cond_destroy (): Destroy condition variable

Pthread_cond_wait (): Wait for the special condition of the condition variable to occur

Pthread_cond_signal (): Wake up the first thread that calls pthread_cond_wait () and enters sleep.

Thread-Local Storage (or pthreads, calledThread-specific data):

Pthread_key_create (): assigns a key to identify the specific data of a thread in a process.

Pthread_setspecific (): sets the thread-specific binding for the specified thread-specific data key.

Pthread_getspecific (): obtains the Key Binding of the call thread and stores the binding in the position pointed to by the value.

Pthread_key_delete (): destroys the specific data key of an existing thread.

 

Tool functions that work together

Pthread_equal (): Compares the thread ID numbers of two threads.

Pthread_detach (): separates threads.

Pthread_self (): query the thread ID

 

For details, see:

Linux multithreading pthread: http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5920936.aspx

Pthread multi-thread learning Summary: http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5921003.aspx

========================================================== ======================================

 

Multi-thread Creation

ReferenceCode:

# Include <stdio. h> <br/> # include <pthread. h> <br/> # include <string. h> <br/> # include <sys/types. h> <br/> # include <unistd. h> <br/> pthread_t main_tid; <br/> void print_ids (const char * Str) <br/>{< br/> pid_t PID; // process id <br/> pthread_t tid; // thread id <br/> pid = getpid (); // obtain the current process id <br/> tid = pthread_self (); // obtain the current thread id <br/> printf ("% s PID: % u TID: % u (0x % x)/n ", <br/> STR, <br/> (unsigned INT) PID, <br/> (UNS Igned INT) tid, <br/> (unsigned INT) tid); <br/>}< br/> void * func (void * Arg) <br/>{< br/> print_ids ("New thread:"); <br/> return (void *) 0 ); <br/>}< br/> int main () <br/>{< br/> int err; <br/> err = pthread_create (& main_tid, null, func, null); // create a thread <br/> If (Err! = 0) {<br/> printf ("create thread error: % s/n", strerror (ERR); <br/> return 1; <br/>}< br/> printf ("main thread: PID: % u TID: % u (0x % x)/n", <br/> (unsigned INT) getpid (), <br/> (unsigned INT) pthread_self (), <br/> (unsigned INT) pthread_self (); <br/> print_ids ("main thread: "); <br/> sleep (1); <br/> return 0; <br/>}< br/>

Running result:

[Work@db-testing-com06-vm3.db01.baidu.com pthread] $ gcc-wall-O pthread_create pthread_create.c-lpthread

[Work@db-testing-com06-vm3.db01.baidu.com pthread] $./pthread_create

Main thread: PID: 12531 TID: 2505487232 (0x9556b380)

Main thread: PID: 12531 TID: 2505487232 (0x9556b380)

New thread: PID: 12531 TID: 1084229984 (0x40a00960)

 

========================================================== ======================================

 

Multithreading condition variable

Reference code:

# Include <stdio. h> <br/> # include <pthread. h> <br/> # include <unistd. h> </P> <p> pthread_mutex_t counter_lock; // mutex lock <br/> pthread_cond_t counter_nonzero; // condition variable <br/> int counter = 0; <br/> int estatus =-1; </P> <p> void * decrement_counter (void * argv); <br/> void * increment_counter (void * argv ); </P> <p> // ******** main function ******** // <br/> int main (INT argc, char ** argv) <br/>{< br/> printf ("counter: % d/N", counter); <B R/> pthread_t thd1, thd2; <br/> int ret; </P> <p> // initialization <br/> pthread_mutex_init (& counter_lock, null ); <br/> pthread_cond_init (& counter_nonzero, null); </P> <p> ret = pthread_create (& thd1, null, decrement_counter, null ); // create thread 1 <br/> If (RET) {<br/> perror ("DEL:/N"); <br/> return 1; <br/>}</P> <p> ret = pthread_create (& thd2, null, increment_counter, null); // create thread 2 <br/> If (RET) {<br/> perror ("Inc:/n "); <Br/> return 1; <br/>}</P> <p> int counter = 0; <br/> while (counter! = 10) {<br/> printf ("counter (main): % d/N", counter); // main thread <br/> sleep (1 ); <br/> counter ++; <br/>}</P> <p> pthread_exit (0); </P> <p> return 0; <br/>}</P> <p> void * decrement_counter (void * argv) <br/>{< br/> printf ("counter (decrement ): % d/N ", counter); <br/> pthread_mutex_lock (& counter_lock); <br/> while (counter = 0) <br/> pthread_cond_wait (& counter_nonzero, & counter_lock); // enter wait, wait for activation (signal) </P> <p> printf ("counter -- (Before): % d/N ", counter); <br/> counter --; // wait until signal is activated. <br/> printf ("counter -- (after): % d/N", counter ); <br/> pthread_mutex_unlock (& counter_lock); </P> <p> return & estatus; <br/>}</P> <p> void * increment_counter (void * argv) <br/>{< br/> printf ("counter (increment ): % d/N ", counter); <br/> pthread_mutex_lock (& counter_lock); <br/> If (counter = 0) <br/> pthread_cond_signal (& counter_nonzero ); // activation (signal) blocking (wait) thread (the signal thread is executed first, and then the wait thread is executed) </P> <p> printf ("counter ++ (Before): % d/N", counter); <br/> counter ++; <br/> printf ("counter ++ (after): % d/N", counter); <br/> pthread_mutex_unlock (& counter_lock ); </P> <p> return & estatus; <br/>}< br/>

Running result:

[Work@db-testing-com06-vm3.db01.baidu.com pthread] $ gcc-wall-O pthread_cond2 pthread_cond2.c-lpthread

[Work@db-testing-com06-vm3.db01.baidu.com pthread] $./pthread_cond2

Counter: 0

Counter (main): 0

Counter (decrement): 0

Counter (increment): 0

Counter ++ (Before): 0

Counter ++ (after): 1

Counter -- (Before): 1

Counter -- (after): 0

Counter (main): 1

Counter (main): 2

Counter (main): 3

Counter (main): 4

Counter (main): 5

Counter (main): 6

Counter (main): 7

Counter (main): 8

Counter (main): 9

 

Detailed explanation, See: http://blog.csdn.net/Sunboy_2050/archive/2010/11/24/6031723.aspx

========================================================== ======================================

 

Create special data keys with multiple threads

Reference code:

# Include <stdio. h> <br/> # include <pthread. h> <br/> # include <unistd. h> </P> <p> pthread_key_t key; // declare the parameter key </P> <p> void echomsg (void * Arg) // destructor <br/>{< br/> printf ("destruct executed in thread = % u, Arg = % P/N ", <br/> (unsigned INT) pthread_self (), <br/> Arg); <br/>}</P> <p> void * child_1 (void * Arg) <br/>{< br/> pthread_t tid; </P> <p> tid = pthread_self (); <br/> printf ("% s: thread % u enter/N ", (char *) Arg, (unsigned INT) tid); </P> <p> pthread_setspecific (Key, (void *) tid ); // value (TID) bound to the key value <br/> printf ("% s: thread % u returns % P/N ", // % P indicates the output pointer format <br/> (char *) Arg, <br/> (unsigned INT) tid, <br/> pthread_getspecific (key )); // obtain the value of the key value <br/> sleep (1); <br/> return NULL; <br/>}</P> <p> void * child_2 (void * Arg) <br/>{< br/> pthread_t tid; </P> <p> tid = pthread_self (); <br/> printf ("% s: thread % u enter/N", (char *) Arg, (unsigned INT) tid); </P> <p> pthread_setspecific (Key, (void *) tid); <br/> printf ("% s: thread % u returns % P/N ", <br/> (char *) Arg, <br/> (unsigned INT) tid, <br/> pthread_getspecific (key )); <br/> sleep (1); <br/> return NULL; <br/>}</P> <p> // ******** main function ******* // <br/> int main (void) <br/>{< br/> pthread_t tid1, tid2; </P> <p> printf ("Hello main/N "); </P> <p> pthread_key_create (& Key, echomsg); // create a key </P> <p> pthread_create (& tid1, null, child_1, (void *) "child_1"); // create a thread with parameters, which must be forcibly converted <br/> pthread_create (& tid2, null, child_2, (void *) "child_2 "); </P> <p> sleep (3); <br/> pthread_key_delete (key); // clear the key <br/> printf ("Bye main/N "); </P> <p> pthread_exit (0); <br/> return 0; <br/>}< br/>

Running result:

[Work@db-testing-com06-vm3.db01.baidu.com pthread] $ gcc-wall-O pthread_setspecific pthread_setspecific.c-lpthread
[Work@db-testing-com06-vm3.db01.baidu.com pthread] $./pthread_setspecific
Hello main
Child_1: thread 1084229984 enter
Child_1: thread 1084229984 returns 0x40a00960
Child_2: thread 1094719840 enter
Child_2: thread 1094719840 returns 0x41401960
Destruct executed in thread = 1084229984, Arg = 0x40a00960
Destruct executed in thread = 1094719840, Arg = 0x41401960
Bye main

 

Additional reference -- function prototype:

POSIX defines two APIs for creating and canceling TSD:

Int pthread_key_create (pthread_key_t * Key, void (* destr_function) (void *)) To log out of a TSD instance, use the following API: Int pthread_key_delete (pthread_key_t key) Int pthread_setspecific (pthread_key_t key, const void * pointer)
Void * pthread_getspecific (pthread_key_t key) Reference URL: Http://blog.sina.com.cn/s/blog_46d528490100lxm0.html Http://xunet.blog.51cto.com/138167/22011(Recommended)

 

========================================================== ======================================

Create special data keys with multiple threads

Reference code:

# Include <stdio. h> <br/> # include <pthread. h> <br/> # include <unistd. h> </P> <p> pthread_once_t once = pthread_once_init; // declare the variable </P> <p> // The once_run () function is executed only once, in which thread is the execution variable <br/> // although pthread_once (& once, once_run) appears in two threads <br/> // function prototype: int pthread_once (pthread_once_t * once_control, void (* init_routine) (void) <br/> void once_run (void) <br/>{< br/> printf ("FUNC: % s in thread: % u/N ", <br/> _ FUNC __, <br/> (unsigned INT) pthread_self ()); <br/>}</P> <p> void * child_1 (void * Arg) <br/>{< br/> pthread_t tid; </P> <p> tid = pthread_self (); <br/> pthread_once (& once, once_run); // call once_run <br/> printf ("% s: thread % d returns/N ", (char *) Arg, (unsigned INT) tid); </P> <p> return NULL; <br/>}</P> <p> void * child_2 (void * Arg) <br/>{< br/> pthread_t tid; </P> <p> tid = pthread_self (); <br/> pthread_once (& once, once_run); // call once_run <br/> printf ("% s: thread % d returns/N ", (char *) Arg, (unsigned INT) tid); </P> <p> return NULL; <br/>}</P> <p> // ******** main ******* // <br/> int main (void) <br/>{< br/> pthread_t tid1, tid2; </P> <p> printf ("Hello main/N"); <br/> pthread_create (& tid1, null, child_1, (void *) "child_1"); <br/> pthread_create (& tid2, null, child_2, (void *) "child_2 "); </P> <p> pthread_join (tid1, null); // The main thread waits for the thread tid1 to return. <br/> pthread_join (tid2, null ); // The main thread waits for the tid2 thread to return <br/> printf ("Bye main/N"); </P> <p> return 0; <br/>}< br/>

Running result:

Work@db-testing-com06-vm3.db01.baidu.comPthread] $ gcc-wall-O pthread_once pthread_once.c-lpthread
[Work@db-testing-com06-vm3.db01.baidu.com pthread] $./pthread_once
Hello main
FUNC: once_run in thread: 1084229984
Child_1: thread 1084229984 returns
Child_2: thread 1094719840 returns
Bye main

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.