Linux programming-synchronization with Semaphores (12th chapter)

Source: Internet
Author: User
Tags mutex semaphore

12.5.2 synchronizing with mutexes Another way of synchronizing access in a multithreaded program is to use Mutex Amount. it allows the programmer to lock an object so that only one thread can access it at a time. To control access to critical code, you must lock a mutex before entering the code, and then unlock it after you complete the operation.
The basic functions for mutexes are very similar to the functions used for semaphores, and they are defined as follows:
#include <pthread.c>int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr); int Pthread_mutex_lock (pthread_mutex_t *mutex); int Pthread_mutex_unlock (pthread_mutex_t *mutex); int pthread_mutex_ Destroy (pthread_mutex_t *mutex);
Similar to semaphores, the parameters of these functions are a pointer to an object that was previously declared. For mutexes, this object's type is the property parameter in the Pthread_mutex_t.pthread_mutex_init function, which defaults to fast, The generic pass parameter, NULL, keeps the default property.
Write the program thread4.c, assuming you need to protect access to some key variables, with a mutex to ensure that only one thread can access them at any one time. To make the code of strength easy to read, omit some error checks that should be made on the return value of the mutex lock and unlock call. In software code, It is necessary to check the return value.
/************************************************************************* > File name:thread4.c > DESCRIPTION:THREAD4.C ensures that only one thread accesses the character array Work_area (read (count)/write) at any one time by mutual exclusion > author:liubingbing > Created time:20 July 05, 15 Sunday 20:47 06 seconds > other:thread4.c omits some error checks that should be made on the return value of the mutex lock and unlock call **************************************** /#include <stdio.h> #include <unistd.h> #include <stdlib.h># Include <string.h> #include <pthread.h> #include <semaphore.h>void *thread_function (void *arg); pthread_mutex_t Work_mutex; /* protects both WORK_ACEA and time_to_exit */#define WORK_SIZE 1024char work_area[work_size];int time_to_exit = 0;int mai N () {int res;pthread_t a_thread;void *thread_result;/* pthread_mutex_init Initialize mutex Work_mutex */res = Pthread_mutex_init ( &work_mutex, NULL), if (res! = 0) {perror ("Mutex initialization failed"); exit (exit_failure);} /* Pthread_create Create new thread * A_thread to save the new thread identifier, thread_function to the new line Chengfunction called */res = pthread_create (&a_thread, NULL, thread_function, NULL), if (res! = 0) {perror ("Thread creation failed"); Exit (exit_failure);} /* Pthread_mutex_lock locks the mutex Work_mutex, and if it is already locked, the call will be blocked until it is released */pthread_mutex_lock (&work_mutex);p rintf (" Input some text. Enter ' End ' to finish\n "), while (!time_to_exit) {fgets (Work_area, Work_size, stdin);/* Pthread_mutex_unlock to Mutex Work_ Mutext Unlocking */pthread_mutex_unlock (&work_mutex); while (1) {/* Pthread_mutex_lock pair Mutex Work_mutex locking */pthread_mutex_ Lock (&work_mutex);/* If the first character of Work_area is not null, unlock the mutex Work_mutex and wait for the new thread to execute */if (work_area[0]! = ' + ') {Pthread_ Mutex_unlock (&work_mutex); sleep (1);} else {break;}}} Pthread_mutex_unlock (&work_mutex);p rintf ("\nwaiting for Thread to finish...\n"), res = Pthread_join (A_thread, &thread_result); if (res! = 0) {perror ("thread join Failed"); exit (exit_failure);} printf ("Thread joined\n");p Thread_mutex_destroy (&work_mutex); exit (exit_success);} void *thread_function (void *arg) {sleep (1);/* First tryThe figure Work_mutex the mutex, and if it is already locked, the call will be blocked until it is released. */pthread_mutex_lock (&work_mutex); while (strncmp ("End", Work_area, 3) = 0) {printf ("You input%d characters\n", Strlen (Work_area)-1);/* Notifies the read input thread by setting the first character to NULL, the new thread completes the character statistic */work_area[0] = ' + ';/* Unlocks the mutex Work_mutex, And wait for the main thread to continue running */pthread_mutex_unlock (&work_mutex), sleep (1),/* Lock the mutex Work_mutex, if the lock succeeds, check if the main thread and characters are sent to handle */pthread _mutex_lock (&work_mutex); while (work_area[0] = = ' + ') {/* If no characters are to be processed, unlock the mutex and continue waiting for */pthread_mutex_unlock (&work _mutex); sleep (1);p thread_mutex_lock (&work_mutex);}} /* If work_area= "End", set time_to_exit = 1, then exit */time_to_exit = 1;work_area[0] = ' Thread_mutex_unlock ';p Mutex);p thread_exit (0);}
The new thread first waits 1 seconds, then work_mutex the mutex, and if Work_mutex has been locked, the call will be blocked until the mutex is released. Once access is obtained, first determine if the Work_area is end.
If it is, set time_to_exit=1 ... then exit.
If not, then count the number of characters, set the Work_area first character to null (by setting the first character to NULL, wait for the main thread to read the new character), unlock the mutex Work_mutex, and then wait for the main thread, The mutex is then locked. The loop then determines whether the first character is still null.
If it is, then continue to wait for the main thread (by unlocking, hibernation, locking),
If it is not (indicating that the main thread has read the new character), character statistics are performed.
The main thread first Work_mutex lock the mutex, and then through the time_to_exit to determine whether to jump out of the loop, if not jump out of the loop, then read the character, unlock the mutex, and then loop waiting for the new thread, by locking the mutex, and then determine whether the first character work_area is empty.
If not, then jump out of the loop and read the new characters.
If it is, unlock the mutex, hibernate. Continue the loop.

The use of flowcharts will be better to look at a little, later look for the software to find a more convenient flow chart. Moreover, the method of polling to get results is usually not very good. In actual programming, the semaphore should be used to avoid this situation whenever possible.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux programming-synchronization with Semaphores (12th chapter)

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.