3. Linux multithreading and thread synchronization) 3. Linux multithreading and thread synchronization

Source: Internet
Author: User
3. Linux multithreading and thread synchronization

5) thread private data

All threads in the process share the data space of the process. Therefore, global variables are shared by all threads.But sometimes the thread also needs to save its own private data, then you can create the thread private data (Thread-specific date)TSD.In a thread, private data can be accessed by various functions, but it is blocked by other threads.For example, common variablesErrno, Which returns standard error information. Obviously, it cannot be a local variable. Almost every function can call it, but it cannot be a global variable. OtherwiseAThe output in the thread is probablyBThread error information. To implement such variables, we must use thread data.We create a key for each thread data, which is associated with this key. In each thread, this key is used to represent the thread data, but in different threads, this key represents different data. In the same thread, it represents the same data content.

The thread private data adoptsOne-click multi-valueTechnology, that is, a key corresponds to multiple values. when accessing data, it seems to be accessing the same variable, but actually accessing different data.

Functions for creating private data include:4Items:Pthread_key_create (Create), Pthread_setspecific (Set), Pthread_getspecific (Obtain), Pthread_key_delete (Delete).

# Include <pthread. h>

Int pthread_key_creadte (pthread_key_t * Key, void (* destr_fuction) (void *));

Int pthread_setspecific (pthread_key_t key, const void * pointer ));

Void * pthread_getspecific (pthread_key_t key );

Int pthread_key_delete (ptherad_key_t key );

6) thread synchronization

The biggest feature of a thread is the sharing of resources, butSynchronization problemsIs the difficulty of multi-threaded programming.LinuxMultiple methods are provided to process thread synchronization. The most common methods are mutex lock, condition variable, and asynchronous signal.

1) mutex lock (Mutex)

The lock mechanism is used to synchronize threads. Only one thread is allowed to execute one key part at a time.Code.

Int pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutex_attr_t * mutexattr );

Int pthread_mutex_lock (pthread_mutex * mutex );

Int pthread_mutex_destroy (pthread_mutex * mutex );

Int pthread_mutex_unlock (pthread_mutex *

(1) first initialize the lockInit ()Or static assignmentPthread_mutex_t mutex = pthread_mutex_initialier

Attr_t has:

Pthread_mutex_timed_np: other threads wait for the queue

Pthread_mutex_recursive_np: Nested lock,Allow threads to lock Multiple times,Different threads,Re-compete after unlocking

Pthread_mutex_errorcheck_np: check error,Together,Used thread request lock,ReturnEdeadlk;

Pthread_mutex_adaptive_np: Adaptive lock,Re-compete after unlocking

(2) Locking, Lock, trylock, lockBlocking wait lock, TrylockReturn nowEbusy

(3) Unlock, UnlockThe lock status must be met,And unlocked by the locking thread

(4) Clear the lock, Destroy (The lock is required.Unlock,OtherwiseEbusy ,//In Linux, mutex locks do not occupy memory resources.

Sample Code

?
# Include <cstdio> # Include <cstdlib> # Include <unistd. h> # Include <pthread. h> # Include "iostream" Using Namespace STD; Pthread_mutex_t mutex = pthread_mutex_initializer; Int TMP; Void * Thread ( Void * Arg) { Cout < "Thread ID is" <Pthread_self () <Endl; Pthread_mutex_lock (& mutex ); TMP = 12; Cout < "Now A is" <TMP <Endl; Pthread_mutex_unlock (& mutex ); Return NULL; } Int Main () { Pthread_t ID; Cout < "Main thread ID is" <Pthread_self () <Endl; TMP = 3; Cout < "In main func TMP =" <TMP <Endl; If (! Pthread_create (& ID, null, Thread , Null )) { Cout < "Create thread success! " <Endl; } Else { Cout < "Create thread failed! " <Endl; } Pthread_join (ID, null ); Pthread_mutex_destroy (& mutex ); Return 0; }

 

Compile:G ++-O thread testthread. cpp-lpthread

Note:PthreadLibrary is notLinuxThe default library of the system. The static library is required for connection.Libpthread..Pthread_create ()Create thread and callPthread_atfork ()Function CreationForkProcessingProgramYou need to link the library. Add-LpthreadParameters.

5) thread private data

All threads in the process share the data space of the process. Therefore, global variables are shared by all threads.But sometimes the thread also needs to save its own private data, then you can create the thread private data (Thread-specific date)TSD.In a thread, private data can be accessed by various functions, but it is blocked by other threads.For example, common variablesErrno, Which returns standard error information. Obviously, it cannot be a local variable. Almost every function can call it, but it cannot be a global variable. OtherwiseAThe output in the thread is probablyBThread error information. To implement such variables, we must use thread data.We create a key for each thread data, which is associated with this key. In each thread, this key is used to represent the thread data, but in different threads, this key represents different data. In the same thread, it represents the same data content.

The thread private data adoptsOne-click multi-valueTechnology, that is, a key corresponds to multiple values. when accessing data, it seems to be accessing the same variable, but actually accessing different data.

Functions for creating private data include:4Items:Pthread_key_create (Create), Pthread_setspecific (Set), Pthread_getspecific (Obtain), Pthread_key_delete (Delete).

# Include <pthread. h>

Int pthread_key_creadte (pthread_key_t * Key, void (* destr_fuction) (void *));

Int pthread_setspecific (pthread_key_t key, const void * pointer ));

Void * pthread_getspecific (pthread_key_t key );

Int pthread_key_delete (ptherad_key_t key );

6) thread synchronization

The biggest feature of a thread is the sharing of resources, butSynchronization problemsIs the difficulty of multi-threaded programming.LinuxMultiple methods are provided to process thread synchronization. The most common methods are mutex lock, condition variable, and asynchronous signal.

1) mutex lock (Mutex)

The lock mechanism is used to synchronize threads. At the same time, only one thread is allowed to execute the code of a key part.

Int pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutex_attr_t * mutexattr );

Int pthread_mutex_lock (pthread_mutex * mutex );

Int pthread_mutex_destroy (pthread_mutex * mutex );

Int pthread_mutex_unlock (pthread_mutex *

(1) first initialize the lockInit ()Or static assignmentPthread_mutex_t mutex = pthread_mutex_initialier

Attr_t has:

Pthread_mutex_timed_np: other threads wait for the queue

Pthread_mutex_recursive_np: Nested lock,Allow threads to lock Multiple times,Different threads,Re-compete after unlocking

Pthread_mutex_errorcheck_np: check error,Together,Used thread request lock,ReturnEdeadlk;

Pthread_mutex_adaptive_np: Adaptive lock,Re-compete after unlocking

(2) Locking, Lock, trylock, lockBlocking wait lock, TrylockReturn nowEbusy

(3) Unlock, UnlockThe lock status must be met,And unlocked by the locking thread

(4) Clear the lock, Destroy (The lock is required.Unlock,OtherwiseEbusy ,//In Linux, mutex locks do not occupy memory resources.

Sample Code

?
# Include <cstdio> # Include <cstdlib> # Include <unistd. h> # Include <pthread. h> # Include "iostream" Using Namespace STD; Pthread_mutex_t mutex = pthread_mutex_initializer; Int TMP; Void * Thread ( Void * Arg) { Cout < "Thread ID is" <Pthread_self () <Endl; Pthread_mutex_lock (& mutex ); TMP = 12; Cout < "Now A is" <TMP <Endl; Pthread_mutex_unlock (& mutex ); Return NULL; } Int Main () { Pthread_t ID; Cout < "Main thread ID is" <Pthread_self () <Endl; TMP = 3; Cout < "In main func TMP =" <TMP <Endl; If (! Pthread_create (& ID, null, Thread , Null )) { Cout < "Create thread success! " <Endl; } Else { Cout < "Create thread failed! " <Endl; } Pthread_join (ID, null ); Pthread_mutex_destroy (& mutex ); Return 0; }

 

Compile:G ++-O thread testthread. cpp-lpthread

Note:PthreadLibrary is notLinuxThe default library of the system. The static library is required for connection.Libpthread..Pthread_create ()Create thread and callPthread_atfork ()Function CreationForkYou need to link the library when processing the program. Add-LpthreadParameters.

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.