Linux Process synchronization Method summary __linux

Source: Internet
Author: User
1. Lock and unlock #inlcude <pthread.h> int pthread_mutex_lock (pthread_mutex_t *mptr);     int Pthread_mutex_trylock (pthread_mutex_t *nptr); int Pthread_mutex_unlock (pthread_mutex_t *mptr);
Mutual-exclusion locks are collaborative locks. This means that if the shared data is a linked list, all threads manipulating the list must acquire the lock before it is actually manipulated.     However, there is no way to prevent a thread from manipulating the list without first acquiring the mutex.         struct{pthread_mutex_t Mutex;         int Buff[max];         int nput;     int nval; }shared={pthread_mutex_initializer}; Producer-consumer issues multiple producers vs. individual consumers, we only consider the problem of synchronization between producers, and do not test the synchronization between producers and consumers, as we ensure that all producers are created before creating consumers. Producer Code: void *produce (void *arg)
{for (;;)         {Pthread_mutex_lock (&shared.mutex);             if (shared.nput>=nitems) {pthread_mutex_unlock (&shared.mutex);         return NULL;     } Shared.buff[shared.nput]=shared.nval;     shared.nput++;     shared.nval++;     Pthread_mutex_unlock (&shared.mutex);     * ((int*) arg) +=1; }    }
Contrast locks and waits for producers and consumers, where consumers are created immediately after the producer is created, so synchronous producers and consumers, consumers cannot go to the unused buffers, and in the absence of conditional variables, the consumer needs a for (;;) Polling for producer products, here we need another type of synchronization that allows a thread (process) to sleep to an event--that's the function of the conditional variable.
2. Conditional variable mutexes are used for locking, and condition variables are used for waiting. These two different types of synchronization are required.     The type of a condition variable is a pthread_cond_t variable.     int pthread_cond_wait (pthread_cond_t *cptr,pthread_mutex_t *mptr);     int pthread_cond_signal (pthread_cond_t *cptr);     The "conditions" by which these functions are waiting or notified are defined by our choice: we test this condition in code. Each condition variable has a mutex associated with it. When we call pthread_cond_wait to wait for a certain condition to be true, we also specify the address of its condition variable and the associated mutex address.     Send signal code to conditional variable: struct{pthread_mutex_t mutex;     pthread_cond_t cond; Maintain the variable}var={pthread_mutex_initializer of this condition, Pthread_mutex_initializer,...}; Pthread_mutex_lock (&var.mutex); Set the condition to True pthread_cond_signal (&var.cond);
Test the condition and go to sleep to wait for the condition to become true: Pthread_mutex_unlock (&var.mutex);  while (condition is false) pthread_cond_wait (&var.cond,&var.mutex); Modify Condition Pthread_mutex_unlock (&var.mutex);
-----------------------------------------------call Pthread_cond_wait (&nready.cond,&nread.mutex) The process will go to sleep, The function performs the following two actions (1) unlocks the mutex Nread.mutex (2) and puts the calling thread into sleep until another thread calls Pthread_cond_signal on the condition variable. Pthread_cond_wait Nready.mutex Lock the mutex before returning. 3. Read and write the lock after the introduction of the bar 4. Semaphore semaphore is a primitive used to provide synchronization between different threads of different processes or a given process. POSIX provides two types of semaphores: a well-known semaphore and a memory based semaphore, which is also called a nameless semaphore.

We mainly study the nameless semaphore (1) int sem_wait (sem_t *sem); int sem_trywait (sem_t *sem); Tests the value of the specified semaphore, and if the value is greater than 0, subtract 1 and return it immediately. If the value is equal to 0, the calling thread is put into sleep until the value becomes greater than 0, then it is reduced by 1, and the function then returns.
Sem_trywait does not sleep when the semaphore equals 0 o'clock, but returns a eagin error. If interrupted by a signal, sem_wait may also return prematurely, and the error returned is EINTR.
int Sem_getvalue (sem_t *sem,int *valp); When a thread finishes using a semaphore, it should call Sem_post. If the semaphore is currently locked, the return value is 0, or a negative number whose absolute value waits for the thread.
Mutex, condition variable, semaphore difference: First: The mutex must always be threads unlocked by the line to which it is locked; the semaphore has no such limit: one thread can wait for a semaphore, and another thread can hang the semaphore.
Second, since each semaphore has a value associated with it, it is added 1 by the suspend operation, minus 1 by the wait operation, so any thread can hang out a signal (for example, to change his value from 0 to 1), even if there was no thread waiting for the semaphore to become a positive number. However, if a thread calls Pthread_cond_signal, but there is no thread blocking the pthread_cond_wait call, the signal destined for the corresponding condition variable will be lost.
Finally, in a variety of synchronization techniques (mutexes, conditional variables, read-write locks, semaphores), the only function that can be invoked safely from a signal handler is sem_post.
The mutex is optimized for locking, and the conditional variable is waiting to be optimized, and the semaphore can be used for both locking and waiting, so it can lead to more overhead.
Create nameless semaphore: int sem_init (sem_t *sem,int shared,unsigned int value); int Sem_destroy (sem_t *sem);
SEM: Point to the sem_t variable that the application must allocate. Shared:0, then the initialized semaphore is shared among the threads of the same process, otherwise, the semaphore is shared between processes (including parent-child processes, so this parameter is also 1 between parent-child processes), and when shared is not zero, the semaphore must be placed in some type of shared memory area. And even all processes that will use it have access to that shared memory area. Value: Initial value of the semaphore
When you do not need to use a name associated with a well-known semaphore, you can switch to a memory based semaphore. When different processes that are unrelated to each other need to use semaphores, a well-known semaphore is usually used.     Its name is the means by which each process identifies the semaphore. As we have said in Figure 1-3, the memory-based semaphore has at least the continuity of the process, but their true persistence depends on the type of memory area where the semaphore is stored. The semaphore persists as long as the memory area containing a memory semaphore remains in effect.
If a memory-based semaphore is shared by each thread within a single process (the shared parameter of Sem_init is 0), then the semaphore has the continuity of the process and disappears when the process terminates. If a memory-based semaphore is shared between different processes (the Sem_init shared is 1), then the semaphore must be in shared memory, so that semaphore continues as long as the shared area remains. The shared memory area has the persistence of the kernel, which means that the server can create a shared memory area in which to initialize a POSIX-based semaphore and then terminate. After a period of time, one or more customers can open the shared memory area to access the memory-based semaphore that is stored in it.

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.