Linux programming exercises-multithreading 3-mutex

Source: Internet
Author: User

Mutex refers to mutually exclusive locks. It is a semaphores that are often used to prevent two processes or threads from accessing the same shared resources at the same time.

1. Data Type:

In Linux, the thread mutex data type is pthread_mutex_t. We define a mutex data as follows:

Pthread_mutex_t mutex;

 

2. Function Description:
Header file: pthread. h

(1). mutex lock initialization:

 

Function prototype: int pthread_mutex_init (pthread_mutex_t * mutex,

Const pthread_mutexattr_t * mutexattr );
Function input value: mutex.

Mutexattr: pthread_mutex_initializer: Creates a fast mutex lock.

Pthread_recursive_mutex_initializer_np: Creates a recursive mutex lock.

Pthread_errorcheck_mutex_initializer_np: creates an error mutex lock.

Function return value: Success: 0

Error:-1
(2). mutex operation function

Int pthread_mutex_lock (pthread_mutex_t * mutex); // lock

Int pthread_mutex_trylock (pthread_mutex_t * mutex); // The lock is blocked only when the mutex is locked.

Int pthread_mutex_unlock (pthread_mutex_t * mutex); // unlock

Int pthread_mutex_destroy (pthread_mutex_t * mutex); // clear the mutex lock

Function input value: mutex.

Function return value: Success: 0

Error:-1

3. Usage:

Struct mutex;

Mutex_init (& mutex);/* definition */

...
Mutex_lock (& mutex);/* Get mutex lock */

.../* Critical resource */

Mutex_unlock (& mutex);/* release mutex lock */

 

 

Finally, let's start an exercise: We create two threads, access the global variable gnum, modify it, and print it out.

[CPP]View plaincopy

  1. /* Mutex. C */
  2. # Include <stdlib. h>
  3. # Include <stdio. h>
  4. # Include <pthread. h>
  5. # Include <errno. h>
  6. /* Global variable */
  7. Int gnum = 0;
  8. /* Mutex */
  9. Pthread_mutex_t mutex;
  10. /* Declare the thread to run the Service Program */
  11. Static void pthread_func_1 (void );
  12. Static void pthread_func_2 (void );
  13. Int main (void)
  14. {
  15. /* Thread identifier */
  16. Pthread_t pt_1 = 0;
  17. Pthread_t pt_2 = 0;
  18. Int ret = 0;
  19. /* Mutex initialization */
  20. Pthread_mutex_init (& mutex, null );
  21. /* Create thread 1 and thread 2 respectively */
  22. Ret = pthread_create (& pt_1, // thread ID pointer
  23. Null, // default attribute
  24. (Void *) pthread_func_1, // run the Function
  25. Null); // No Parameter
  26. If (Ret! = 0)
  27. {
  28. Perror ("pthread_cmdcreate ");
  29. }
  30. Ret = pthread_create (& pt_2, // thread identifier pointer
  31. Null, // default attribute
  32. (Void *) pthread_func_2, // run the Function
  33. Null); // No Parameter
  34. If (Ret! = 0)
  35. {
  36. Perror ("pthread_2_create ");
  37. }
  38. /* Wait for the end of thread 1 and thread 2 */
  39. Pthread_join (pt_1, null );
  40. Pthread_join (pt_2, null );
  41. Printf ("main programme exit! /N ");
  42. Return 0;
  43. }
  44. /* Service program of thread 1 */
  45. Static void pthread_func_1 (void)
  46. {
  47. Int I = 0;
  48. For (;;)
  49. {
  50. Printf ("this is pthread1! /N ");
  51. Pthread_mutex_lock (& mutex);/* obtain the mutex lock */
  52. /* Note: This is to prevent the thread from being preemptible, so that a thread can access mutex resources multiple times during another thread sleep. Therefore, sleep must be called after obtaining the mutex lock */
  53. Sleep (1 );
  54. /* Critical resources */
  55. Gnum ++;
  56. Printf ("thread1 add one to num: % d/N", gnum );
  57. Pthread_mutex_unlock (& mutex);/* release mutex lock */
  58. }
  59. }
  60. /* Service program of thread 2 */
  61. Static void pthread_func_2 (void)
  62. {
  63. Int I = 0;
  64. For (;;)
  65. {
  66. Printf ("this is pthread2! /N ");
  67. Pthread_mutex_lock (& mutex);/* obtain the mutex lock */
  68. /* Note: This is to prevent the thread from being preemptible, so that a thread can access mutex resources multiple times during another thread sleep. Therefore, sleep must be called after obtaining the mutex lock */
  69. Sleep (1 );
  70. /* Critical resources */
  71. Gnum ++;
  72. Printf ("thread2 add one to num: % d/N", gnum );
  73. Pthread_mutex_unlock (& mutex);/* release mutex lock */
  74. }
  75. Pthread_exit (0 );
  76. }

Then compile and run the program. We can see that the thread 1 and 2 access the shared resources in a peaceful way.

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.