UNIX Network programming: mutexes and condition variables

Source: Internet
Author: User

In the network programming, is generally multithreaded programming, this arises a problem: data synchronization and sharing. The mutex and condition variables are the two most basic components to allow the data to be shared between threads or processes. They can always be used to synchronize multiple threads in a process.
Before entering the mutex and the condition variable, we first introduce some related functions of multithreading:

Multithreading simple introduction and related functions:
Typically, a process consists of multiple threads, each of which is the basic unit of CPU scheduling, multithreading can be said to be in the shared memory space in parallel with multi-channel execution, compared to the process, the thread has the following advantages:
Reduce system scheduling overhead. Because threads do not have resources at all, the switching of threads is very rapid and the speed of operation is increased, and the execution of the program is more efficient.
Easy communication between threads. Because multiple threads of the unified process share resources, the data for one thread can be used directly by other threads, making the exchange of data between them easier and faster.
Improve the design structure. The complex process can be divided into several independent threads, the program structure is clear and the module is stronger.
Threading technology was presented as early as the 1960s, but it was not until the mid 1980s that multithreading was actually applied to the operating system.
Threads have two implementations: the user-state thread and kernel-mind thread, the current thread is the main implementation method is the user-state thread, the user-state multi-threaded procedures do not need a specific kernel support at runtime, scheduling switch between the same process thread, there is no need to call system calls, which makes the thread operation of the system overhead is reduced, However, in the scheduling of multiple threads in a process can not play the advantages of multi-processing, the implementation of the kernel mentality thread allows threads in different processes to be dispatched according to the same scheduling method, which facilitates the concurrency advantage of multiprocessor.

2, Linux multi-threaded operation
To write a multi-threaded program under Linux, you need to use the header file Pthread.h, the header file defines the thread operation related APIs and data structure, compile the link need to add the compiler's –lpthread option, indicate the required line libraries file.
1. Thread creation function

const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

Parameter 1 (thread): The thread tid number used to create the thread.
Parameter 2 (attr): Used to set the properties of the new thread, if you use the default properties, you can fill in null, you can also use the system-provided functions, set the properties of the thread to the properties we need. The properties of the thread mainly include the separation property, the binding property, the Dispatch property, the stack attribute, the Inheritance property, etc., the property structure is pthread_attr_t, in the usr/include/ As defined in Pthread.h, property values cannot be set directly and need to be manipulated using related functions, and the initialized function is Pthread_attr_init (). The thread must be created before the function pthread_create ().
Parameter 3: The entry address of the action performed by the thread suo.
Parameter 4: The parameter of the function executed by the thread, without the flower being null.
2. Wait for the thread to end the function:

intvoid

Used to wait for the end of a specified thread.
Parameter 1: The TID number of the thread to wait for;
Parameter 2: The return value of the status of the thread in existence, half of which is set to null.

3. Thread termination function

void pthread_exit(void *retval);

In the result of a non-implicit call to the main thread, the startup function of any of the threads returns Pthread_exit (), using the return value of the function as the exit state of the thread.
Allow other threads to continue execution, the main thread should terminate Pthread_exit () by calling

Mutual exclusion Lock:
Mutexes are only mutually exclusive, and it is the most basic form of synchronization. Mutexes are used to protect critical sections (areas that are accessible to different threads of the same process) to ensure that only one thread executes code at any time, or that only one process executes it at any time.
The mutex is essentially a lock that provides protected access to shared resources, two states of mutex, lock and unlock, to guarantee that only one thread can use shared resources for a period of time.

To protect a critical section large values operate as follows:

pthread_mutex_lock(...);      //对某个线程上锁临界区;pthread_mutex_unlock(...);   //对相应的线程解锁

Under Linux, the mutex data type of a thread is pthread_mutex_t, and the function involved in the mutex operation mainly includes:
1. Initialize the mutex lock
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);

Parameter 1: The address of a Metux type of mutex.
Parameter 2: The property of the new mutex is specified. If the parameter attr is NULL, the default mutex property is used, and the default property is a quick mutex. The properties of the mutex are specified when the lock is created, there is only one lock type attribute in the Linuxthreads implementation, and the different lock types behave differently when attempting to lock an already locked mutex.
When the Pthread_mutexattr_init () function completes successfully, it returns zero, and any other return value indicates an error occurred. After the function executes successfully, the mutex is initialized to a locked state.

2. Thread Lock function
int pthread_mutex_lock(pthread_mutex_t *mutex);

3. Thread attempt lock function
int pthread_mutex_trylock(pthread_mutex_t *mutex);

4. Line Threads Unlocked function
int pthread_mutex_unlock(pthread_mutex_t *mutex);

5. Thread Destroy Mutex function
int pthread_mutex_destroy(pthread_mutex_t *mutex);

Condition variables:

2. Condition variables
A mutex is likely to cause a deadlock, introducing a conditional variable that allows a thread to block and wait for a signal sent by another thread, using a condition variable to block the thread atomically until a condition is met, to avoid being busy, and so on.
The condition variable is used together with the mutex, the mutex is mainly used to guarantee the mutual exclusion of the critical section, while the condition variable is used for the blocking wait of the thread, when the mutex lock enters the critical section, if the condition is not satisfied, the thread will turn to wait, wait for the condition to be satisfied and then wake up to execute.

The condition variable type is pthread_cond_t, and the related operation function is:
1. Initialization of functions:
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
Creates a new condition variable by parameter attr the specified property.
Parameter 1: The condition variable that you want to create.
Parameter 2: The property of the condition variable. Attr is null, the default attribute is used to create the condition variable. This is the initialization of a dynamically allocated mutex, which can be initialized directly for a statically assigned mutex: pthread_cond_tcond=PTHREAD_COND_INITIALIZER;
Any condition variable must be initialized before it is used, and can be reinitialized only once (if it is a conditional variable that is destroyed).

2. Notification condition variable function
(1) int pthread_cond_signal(pthread_cond_t *cond);
This function is used to dismiss a blocking state of a thread waiting for a specified event, and if there are several threads pending waiting for the condition variable, the call evokes only one thread, and the invoked thread is not determined.
Parameter cond: Specifies the condition amount of the event.

(2) int pthread_cond_broadcast(pthread_cond_t *cond);
This function is used to unblock all threads waiting for this condition variable.
Parameter cond: Specifies the condition variable for the event.

3. Wait for the condition variable function
(1) int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
The function is to wait for an event (condition variable) notification, such as the example above, after test A is 0, if it is not 0, then call the function, suspend the thread, wait for notification of the corresponding condition variable event (blocked thread until another thread calls Pthread_cond_ The signal or Pthread_cond_broadcast function is awakened only if the corresponding condition variable is placed). These are directly related to this particular condition variable because the thread that waits for a particular condition variable is a queue.
Parameter 1 (COND): The condition variable that is waiting.
Parameter 2 (Mutex): the mutex used.

(2) int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
This function has a time parameter more than the previous function, which is to wait for an event to occur within a specified time, and if it is not awakened within the specified time, then the function returns a value of Etimedout (110) indicating a timeout. This is very useful and can be used to specify the thread sleep time, it is worth noting that this time parameter is absolute time, not time interval.
Parameter 1 (COND): The condition variable that is waiting.
Parameter 2 (Mutex): the mutex used.
Parameter 3 (abstime): Specifies the time range to wait.

In general, the notification condition variable function (pyhread_cond_signal ()) is used in conjunction with the Wait condition variable function (pthread_cond_wait ()) to protect the shared resource.

Here is a simple program code to show the "magic" of the mutex and the condition variable:
Creates a single thread that handles value in odd and even numbers, and manages the shared data value with a mutex and a condition variable.

#include <unistd.h>#include <stdlib.h>#include <pthread.h>#include <time.h>#include <stdio.h>#define max_sizeint value=0;p thread_mutex_t mutexes;//Define a global mutexPthread_cond_t Dan, Shuang;//define two conditional variables to represent singular and even-numbered signalsvoid* PTHREAD_FUN1 (void*arg) {pthread_mutex_lock (&mutex);//On shared data value lockout     while(value< max_size) {if(value%2==1){//value is an odd numberprintf"fun1 value =%d\n",value);value++;//value value plus 1Pthread_cond_signal (&shuang);//Send as a dual signal. Notifies the even-numbered processing thread pthread_fun2 ().}Else{//value is not an odd numberPthread_cond_wait (&dan, &mutex);//blocking the program and unlocking the mutex. Wait for the condition variable dan to be received before locking and keep the function running. }} pthread_mutex_unlock (&mutex);//Line threads unlocked. }void* PTHREAD_FUN2 (void*arg) {pthread_mutex_lock (&mutex);//Lock the thread, and if the mutex has been locked, the program is blocked at that point until the other thread unlocks it to the resource.      while(value< max_size) {//If Vallue is within the predetermined range        if(value%2==0){//value is evenprintf"fun2 value =%d\n",value);value++; Pthread_cond_signal (&dan);//Send as a dual signal. Notifies the odd processing thread pthread_fun1 ().}Else{pthread_cond_wait (&shuang, &mutex);//blocking the program and unlocking the mutex. Wait for the condition variable to be received Shuang and then lock and keep the function running}} pthread_mutex_unlock (&mutex);unlock the mutex before the thread finishes running. }intMain () {pthread_mutex_init (&mutex,null);//Mutex initializationpthread_t tid[2]; Pthread_create (&tid[1], NULL, pthread_fun2, &tid[0]);//Create a thread to perform the pthread_fun2 () operation. Sleep1); Pthread_create (&tid[0], NULL, PTHREAD_FUN1, NULL);//Create a thread to perform the PTHREAD_FUN1 () operation. Pthread_join (tid[0], NULL);//wait for thread 1 to endPthread_join (tid[1], NULL);//wait for thread 2 to endPthread_mutex_destroy (&mutex);//Destroy the mutex.     return 0;}

UNIX Network programming: mutexes and condition variables

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.