Thread Synchronization and mutex: mutex lock

Source: Internet
Author: User

Thread Synchronization and mutex: mutex lock
Why do we need mutex lock?

In a multitasking operating system, the same resource may be used for multiple tasks running simultaneously. This process is a bit similar. In the company department, while I was using a printer to print something (not printing enough), others just used a printer to print something at the moment, if you do not do anything, the printed items will be messy.

 

Below we use a program to simulate this process. Thread 1 needs to print "hello", thread 2 needs to print "world", and the printed content will be disordered without any processing:

 

[Cpp]View plaincopy

  1. # Include
  2. # Include
  3. # Include
  4.  
  5. // Printer
  6. Void printer (char * str)
  7. {
  8. While (* str! = '\ 0 ')
  9. {
  10. Putchar (* str );
  11. Fflush (stdout );
  12. Str ++;
  13. Sleep (1 );
  14. }
  15. Printf ("\ n ");
  16. }
  17.  
  18. // Thread 1
  19. Void * thread_fun_1 (void * arg)
  20. {
  21. Char * str = "hello ";
  22. Printer (str); // print
  23. }
  24.  
  25. // Thread 2
  26. Void * thread_fun_2 (void * arg)
  27. {
  28. Char * str = "world ";
  29. Printer (str); // print
  30. }
  31.  
  32. Int main (void)
  33. {
  34. Pthread_t tid1, tid2;
  35.  
  36. // Create two threads
  37. Pthread_create (& tid1, NULL, thread_fun_1, NULL );
  38. Pthread_create (& tid2, NULL, thread_fun_2, NULL );
  39.  
  40. // Wait until the thread ends and reclaim its resources
  41. Pthread_join (tid1, NULL );
  42. Pthread_join (tid2, NULL );
  43.  
  44. Return 0;
  45. }
    The running result is as follows:

     

     

    In fact, the printer is used for processing. When printing, others are not allowed to print the printer. Only when I print the printer, others are allowed to print it. This process is a bit similar. Put the printer in a room and lock the room. This lock is opened by default. When A needs to print the lock, he first checks whether the lock is locked. If not, he goes in and prints the lock in the room. At this moment, B also needs to print, B also checks the lock first, and finds that the lock is locked, and he will wait outside the door. After printing A, B locks out the lock.

     

    There is also a lock in the thread-mutex. mutex is a simple lock method to control access to shared resources. There are only two States of mutex, locks and unlocks ).

     

    The procedure of the mutex lock is as follows:

    1) Lock the mutex lock before accessing the critical area after shared resources.

    2) release the lock on the mutex lock export after the access is completed.

    3) after the mutex lock is applied, any other thread that tries to lock the mutex lock again will be blocked until the lock is released.

     

    The mutex lock data type is:Pthread_mutex_t.

     

    Mutex lock operation

    Header files required by the following functions:

    # Include

     

    1) initialize the mutex lock

    Int pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutexattr_t * attr );

    Function:

    Initializes a mutex lock.

    Parameters:

    Mutex: Mutex lock address. The type is pthread_mutex_t.
    Attr: Sets the mutex attribute. Generally, the default attribute can be used to set attr to NULL.

     

    You can use the macro PTHREAD_MUTEX_INITIALIZER to statically initialize mutex locks, for example:
    Pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    This method is equivalent to calling pthread_mutex_init () with the attr parameter specified by NULL to perform dynamic initialization. The difference is that the PTHREAD_MUTEX_INITIALIZER macro does not perform error checks.

    Return Value:

    Successful: 0. The applied lock is opened by default.

    Failed: Non-0 error code

     

    2) Lock

    Int pthread_mutex_lock (pthread_mutex_t * mutex );

    Function:

    Lock a mutex lock. If the mutex lock is locked, the caller will block it until the lock is unlocked.

    Parameters:

    Mutex: Mutex lock address.

    Return Value:

    Success: 0

    Failed: Non-0 error code

     

    Int pthread_mutex_trylock (pthread_mutex_t * mutex );

    When this function is called, if the mutex lock is not locked, the lock is locked and 0 is returned. If the mutex lock has been locked, the function returns failure, that is, EBUSY.

     

    3) Unlock

    Int pthread_mutex_unlock (pthread_mutex_t * mutex );

    Function:

    Unlock the specified mutex lock.

    Parameters:

    Mutex: Mutex lock address.

    Return Value:

    Success: 0

    Failed: Non-0 error code

     

    4) destroy the mutex lock

    Int pthread_mutex_destroy (pthread_mutex_t * mutex );

    Function:

    Destroys a mutex. After the mutex lock is used, the mutex lock must be destroyed to release resources.

    Parameters:

    Mutex: Mutex lock address.

    Return Value:

    Success: 0

    Failed: Non-0 error code

     

    Mutex lock application instance

    We use the mutex lock to complete the above example. The sample code is as follows:

     

    [Cpp]View plaincopy
    1. # Include
    2. # Include
    3. # Include
    4.  
    5. Pthread_mutex_t mutex; // mutex lock
    6.  
    7. // Printer
    8. Void printer (char * str)
    9. {
    10. Pthread_mutex_lock (& mutex); // lock
    11. While (* str! = '\ 0 ')
    12. {
    13. Putchar (* str );
    14. Fflush (stdout );
    15. Str ++;
    16. Sleep (1 );
    17. }
    18. Printf ("\ n ");
    19. Pthread_mutex_unlock (& mutex); // unlock
    20. }
    21.  
    22. // Thread 1
    23. Void * thread_fun_1 (void * arg)
    24. {
    25. Char * str = "hello ";
    26. Printer (str); // print
    27. }
    28.  
    29. // Thread 2
    30. Void * thread_fun_2 (void * arg)
    31. {
    32. Char * str = "world ";
    33. Printer (str); // print
    34. }
    35.  
    36. Int main (void)
    37. {
    38. Pthread_t tid1, tid2;
    39.  
    40. Pthread_mutex_init (& mutex, NULL); // initialize the mutex lock
    41.  
    42. // Create two threads
    43. Pthread_create (& tid1, NULL, thread_fun_1, NULL );
    44. Pthread_create (& tid2, NULL, thread_fun_2, NULL );
    45.  
    46. // Wait until the thread ends and reclaim its resources
    47. Pthread_join (tid1, NULL );
    48. Pthread_join (tid2, NULL );
    49.  
    50. Pthread_mutex_destroy (& mutex); // destroy the mutex lock
    51.  
    52. Return 0;
    53. }

       


      The running result is as follows:

       

       

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.