Linux Network programming-----> Thread Sync---semaphores

Source: Internet
Author: User

Development using multi-threaded process, it is inevitable that multiple threads concurrently operate the same piece of shared resources, when the operation is all read, there will be no unknown results, once there is a write operation in a thread operation, there will be data out of sync events.

and the reason for the data confusion:


      • debug random (competition for data access)

      • There is a lack of necessary synchronization mechanism between threads    

above three points, the first two points can not be changed. To improve efficiency, transfer data, resources must be shared. As long as the resources are shared, there will be competition between the threads, so that if there is a competitive relationship, the data will become chaotic.

Therefore, only from the 3rd, so that multiple threads when accessing the shared resources, there is mutual exclusion.

Thread synchronization:

means that only one process is allowed to access a resource for a certain amount of time, and no other thread is allowed to operate on that resource during this time.

Synchronization mechanism for Threads:


      • Mutex (mutual exclusion lock)

      • Read/write Lock

      • Condition variable (required with mutex (mutex) to use)

      • Signal Volume

The first two chapters have covered the mutex (mutex), read-write lock, and condition variable, and this chapter describes the key signal volume


The semaphore, also known as the evolutionary version of the mutex---->, can only be accessed by one thread at a time, while the semaphore may be simultaneous with n threads simultaneously.

Because of the large granularity of the mutex, if we want to share some of the data of an object between multiple threads, there is no way to implement the mutex, only the entire data object can be locked. In this way, although it achieves the purpose of guaranteeing the correctness of data when the multi-threaded operation is shared, the concurrency of threads is decreased in the invisible. The thread executes in parallel and becomes a string execution. is no different than using a single process directly.

Signal volume, is a relative compromise of a processing way, not only to ensure synchronization, data is not chaotic, but also to improve thread concurrency.


Let's start by looking at the functions commonly used by conditional variables:

sem_init (sem_t* sem, int pshared, unsigned int value);

Function: Initializes a semaphore

Parameter 1:sem signal Volume

Parameter 2:pshared 0 for threads, 0 (typically 1) for inter-process

Parameter 3:value Specifies the initial value of the semaphore


Sem_destroy (sem_t* sem);

function: Destroys a semaphore

Parameter: Specify an already initialized SEM semaphore


sem_wait (sem_t* sem);

function: Give the semaphore locking (the value of the semaphore as the-operation, if the value of the semaphore at this time is 0 blocking wait)

Parameter: Specify an already-initialized SEM signal volume


sem_post (sem_t* sem);

function: Unlocks the semaphore (the value of the semaphore is the + + operation)

Parameter: Specify an already-initialized SEM signal volume


sem_trywait (sem_t* sem);

Effect: Attempts to locking the semaphore (if the value of the semaphore at this time is 0, return immediately.) Not blocked)

Parameter: Specify an already-initialized SEM signal volume


sem_timedwait (sem_t* sem, const struct timespec* abs_timeout);

function: Attempts to locking the semaphore within a limited time (time is the current absolute time)

Parameter 1: Specify an already initialized SEM semaphore

Parameter 2: Specify the absolute time structure body as follows struct timespec{

time_t tv_sec; Seconds

Long tv_nsec; Na-Sec

};


case: One thread reads user input and another thread prints "Hello World". If the user has no input, a "Hello World" is printed to the screen every 5 seconds, and if the user has input, print "Hello World" to the screen immediately [think]

 #include  <stdio.h> #include  <stdlib.h> #include   <semaphore.h> #include  <pthread.h> #include  <time.h> #include  <string.h> sem_t sem;//Global Semaphore Void* thread_handler (VOID*&NBSP;AGRS) {struct timespec tv = {  time (NULL) +5, 0};//initializes the current time while (1) {//Timed acquisition semaphore sem_timedwait (&SEM,&NBSP;&TV);//If the user has input, print immediately, Otherwise print printf ("hello world\n") after 5 seconds;//Reset Absolute time Tv.tv_sec = time (NULL) +5;tv.tv_nsec = 0;}} Int main (int argc, char* agrv[]) {pthread_t tid;//Initialize semaphore, support between threads, start initial value of 0sem_init (&sem ,  0, 0);//Create Thread pthread_create (&tid, null, thread_handler, null); char buf[ Bufsiz] = { 0 };while (1) {//block read user input fgets (buf, sizeof (BUF),  stdin);//Semaphore value +1sem_ Post (&sem);} Wait for thread to exit Pthread_join (Tid, null); return 0;} 

Tip: There are many applications in the semaphore thread pool. Be proficient.

This article from the "Sea" blog, reproduced please contact the author!

Linux Network programming-----> Thread Sync---semaphores

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.