Linux multithreading--Synchronizing threads with mutex "go"

Source: Internet
Author: User
Tags semaphore strcmp

This article reproduced from: http://blog.csdn.net/ljianhui/article/details/10875883 the previous article, the book connected to one back, in the previous article: Linux multithreading-Using semaphore synchronization thread, We left a question of how to use mutex to thread synchronization, this article will give a detailed explanation of the mutex, and with a mutex to solve the previous article, to use two semaphores to solve only the child thread end the processing and statistics of the input, the main thread can continue to execute the problem. One, what is a mutex mutex is another synchronous access method used in multi-threading, which allows a program 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 the operation is complete. Second, the use of the mutex function is very similar to the function that uses semaphores, they are defined as follows: [CPP]View PlainCopyprint?
    1. #include  <pthread.h>   
    2. int pthread_mutex_init (pthread_mutex_t *mutex, < span class= "keyword" >const pthread_mutexattr_t *mutexattr);   
    3. &NBSP;&NBSP;
    4. int pthread_mutex_lock (Pthread_mutex_t *mutex);   
    5. Li class= "alt" >&NBSP;&NBSP;
    6. int pthread_mutex_unlock (pthread_mutex_t  *mutex);   
    7. &NBSP;&NBSP;
    8. int pthread_ Mutex_destroy (Pthread_mutex_t *mutex);   
Their meaning, as their names show, returns 0 on success, returns an error code on failure, and does not set errno. The arguments in the Pthread_mutex_init function mutexattr Specify the property of the mutex, where we do not care about the property of the mutex, so set it to null and use the default property. Similarly, Pthread_mutex_lock and Pthread_mutex_unlock are atomic operations, and if a thread calls Pthread_mutex_lock trying to lock the mutex, and that mutex is locked (occupied) by another thread, The thread's Pthread_mutex_lock call is blocked until the mutex is unlocked by the other thread, and the Pthread_mutex_lock call is returned. Note that using the default property of the mutex, if the program tries to call Pthread_mutex_lock on an already locked mutex, the program will block, and because the thread that owns the mutex is the thread that is now blocked, the mutex will never be unlocked, which means The program will enter the deadlock state. Be careful when you use it, and be sure to unlock the locked mutex again before locking it in the same thread. Iii. using mutex for thread synchronization The following is a simple multithreaded program that demonstrates how to use mutexes for thread synchronization. In the main thread, we create a sub-thread and pass the array msg as an argument to the child thread, then the main thread calls the function Pthread_mutex_lock locks the mutex, waits for input, and after the input completes, calls the function Pthread_mutex_unlock unlocks the mutex. The Pthread_mutex_lock function that locks the mutex in the thread function returns and executes the code in the child thread. After the thread function turns the lowercase letter of the string into uppercase and counts the number of characters entered, it calls Pthread_mutex_unlock to unlock the mutex so that the main thread can continue to obtain the mutex (that is, to return the lock function) and perform the input function again until the main thread calls Pthread again. The _mutex_unlock unlocks it so that it repeats until the end is entered. The source file is LOCKTHREAD.C and the source code is as follows: [CPP]View PlainCopyprint?
  1. #include <unistd.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. Declaring thread functions and mutexes
  7. void* Thread_func (void *msg);
  8. pthread_mutex_t Mutex;
  9. #define MSG_SIZE 512
  10. int main ()
  11. {
  12. int res =-1;
  13. pthread_t thread;
  14. void *thread_result = NULL;
  15. char Msg[msg_size] = {'} '};
  16. //Initialize mutex, use default Mutex property
  17. res = Pthread_mutex_init (&mutex, NULL);
  18. if (res! = 0)
  19. {
  20. Perror ("Pthread_mutex_init failed\n");
  21. Exit (Exit_failure);
  22. }
  23. //Create a sub-thread and pass MSG as a parameter to the thread function to Thread_func
  24. res = pthread_create (&thread, NULL, Thread_func, msg);
  25. if (res! = 0)
  26. {
  27. Perror ("Pthread_create failed\n");
  28. Exit (Exit_failure);
  29. }
  30. //input string, end at string ' End '
  31. printf ("Input some test.  Enter ' End ' to finish\n ");
  32. //Lock mutex mutex to ensure that only the thread can access the data in MSG at the same time
  33. Pthread_mutex_lock (&mutex);
  34. while (strcmp ("end\n", msg)! = 0)
  35. {
  36. if (strncmp ("TEST", MSG, 4) = = 0)
  37. {
  38. strcpy (msg, "copy_data\n");
  39. }
  40. Else
  41. {
  42. Fgets (msg, msg_size, stdin);
  43. }
  44. //Unlock mutex mutex so that other threads can access the data in MSG
  45. Pthread_mutex_unlock (&mutex);
  46. Sleep (1); //Hibernate for 1 seconds and continue the loop so that other threads have an opportunity to execute
  47. Pthread_mutex_lock (&mutex);
  48. }
  49. Pthread_mutex_unlock (&mutex);
  50. printf ("\nwaiting for Thread finish...\n");
  51. //wait for the child thread to end
  52. res = Pthread_join (thread, &thread_result);
  53. if (res! = 0)
  54. {
  55. Perror ("Pthread_join failed\n");
  56. Exit (Exit_failure);
  57. }
  58. printf ("Thread joined\n");
  59. //Clean up mutex amount
  60. Pthread_mutex_destroy (&mutex);
  61. Exit (exit_success);
  62. }
  63. void* Thread_func (void *msg)
  64. {
  65. int i = 0;
  66. char *ptr = msg;
  67. Sleep (1);
  68. //Lock mutex mutex to ensure that only the thread can access the data in MSG at the same time
  69. Pthread_mutex_lock (&mutex);
  70. while (strcmp ("end\n", msg)! = 0)
  71. {
  72. //Turn lowercase letters into uppercase
  73. For (i = 0; Ptr[i]! = '; ++i ")
  74. {
  75. if (ptr[i] >= ' a ' && ptr[i] <=' z ')
  76. {
  77. Ptr[i] -= ' a '-' a ';
  78. }
  79. }
  80. printf ("You input%d characters\n", i-1);
  81. printf ("to uppercase:%s\n", PTR);
  82. //Unlock mutex mutex so that other threads can access the data in MSG
  83. Pthread_mutex_unlock (&mutex);
  84. Sleep (1); //Hibernate for 1 seconds and continue the loop so that other threads have an opportunity to execute
  85. Pthread_mutex_lock (&mutex);
  86. }
  87. Pthread_mutex_unlock (&mutex);
  88. //Exit thread
  89. Pthread_exit (NULL);
  90. }
The results of the operation are as follows:  program analysis:  The workflow of this program has been made very clear, here first of all in the main function and the thread function Thread_func in the while loop in the function of the sleep (1) statement. A lot of people may think that this sleep (1) is for the child thread to complete its processing and statistics functions, so let the main thread hibernate for 1 seconds to wait for the child thread to finish processing the statistical work. It's true that the sub-threads are doing a very simple job, and in 1 seconds you can actually handle the statistics. But the sleep here (1) is not to achieve this function, the two loops of sleep (1) is to let other threads have the opportunity to be executed, if there is no such statement between the lock and unlock, then the current thread will always be in the loop to obtain the mutex amount, Because other threads do not have the time to execute its code, it is necessary to use such a statement to give other threads a chance to run. If the child thread takes more than 1 seconds to execute, the program will run normally.   In this case, in the main thread, when the input data is complete and the mutex is unlocked, does not immediately loop to lock it, at this time the child thread has the opportunity to execute, it will lock the mutex, similarly, when it processing statistics input data, it before entering the next cycle, it also sleeps 1 seconds, Let the main thread have the opportunity to run again. When the main thread is able to execute, it depends on when the child thread unlocks the mutex. Because if the child thread owns (locks) The mutex, the function pthread_mutex_lock in the main thread does not return, leaving the main thread in a blocked state.   In other words, the main thread can continue execution and write data to the MSG only after the child thread has finished processing and counting the inputs. See here, you should know that before the use of semaphores, we use a more semaphore is also to achieve this goal. So when we enter test, the program has two inputs, but it still works, which solves the problem of using a semaphore before.   The role of semaphores and mutexes are mutually exclusive devices that protect code snippets, and they are very similar. However, in this case, the same function is achieved with the use of semaphores, if the semaphore is used, then two semaphores are required, and only one is needed if the mutex is used. It can be said that the use of mutexes is simpler in this case. But I think the use of mutexes is more likely to make mistakes, and we can see in this example that we need to use the sleep statement to get other threads to execute, but in a program that uses semaphores, it doesn't need to use sleep, which is relatively straightforward. I know it may be my implementation is not good, but for the use of mutex, I think for a long time also thought not to use sleep method.

Linux multithreading-Synchronizing threads with mutexes "Go"

Related Article

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.