Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Linux Thread Synchronization     - Shell script to delete empty folders recursively (Linux)

- Difference LVS three scheduling modes (Server)

- GAMIT baseline solution using batch were counted (Linux)

- Nagios plugin installation tutorial of Nrpe (Linux)

- Docker Build a Java compiler environment (Linux)

- How to view the Linux QPS (Linux)

- C ++ overloaded stream insertion operator and the stream extraction operator (Programming)

- Node.js development environment deployment (Server)

- MySQL and MariaDB traditional master-slave cluster configuration (Database)

- DM9000 timing settings (Programming)

- Installation and deployment of Hadoop 2.7.1 on Ubuntu 14.04 LTS (Server)

- MySQL innodb_table_stats table does not exist solution (Database)

- CentOS6.5 setup Oracle 11gR2 startup (Database)

- 3 tips Linux command (Linux)

- SSL VPN SSL VPN access to security websites patron (Linux)

- Tune in high resolution to 1280x800 in Fedora 14 (Linux)

- Use PXE with kickstart to install Linux automatically (Linux)

- CentOS 6.5 / Linux restart network card being given Determining if ip address x.x.x.x is already in use (Linux)

- Php and MySQL command add to the environment variable method in Linux system (Linux)

- Linux RAID Set RAID 10 or 0 + 1 (Linux)

 
         
  Linux Thread Synchronization
     
  Add Date : 2018-11-21      
         
         
         
  I. Overview

Mutex is a mechanism to synchronize threads to protect multi-threaded shared resources. The same time, allows only one thread to access the critical section.

Mutex workflow: Create a mutex to lock the mutex at the beginning of the call position critical region, unlock call in the end position of the critical section. When the kernel thread scheduling to give priority to a start position of the critical section, the thread of execution locking calls and enters the critical area of resource operations. At this time other threads are then dispatched to the kernel here, since the mutex is locked state, the lock will always get back up here, lead to other threads can not enter the critical region, just until the thread enters the critical zone leaving the critical section and perform the unlock calls.

II. Function Interface

1. Initialize the mutex

Mutex is a variable pthread_mutex_t type.

1.1: The initialization macro constants:

1 pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
1.2: The initialization function:

1 #include
2
3 int pthread_mutex_init (pthread_mutex_t * restrict mutex, const pthread_mutexattr_t * restrict attr);
mutex: mutex structure pointer

attr: mutex attribute structure pointer

2. Set mutex attribute

1 #include
2
3 int pthread_mutexattr_settype (pthread_mutexattr_t * attr, int type);
attr: mutex attribute structure pointer

type: PTHREAD_MUTEX_NORMAL (default property), PTHREAD_MUTEX_ERRORCHECK (will be checked for errors, more slowly), PTHREAD_MUTEX_RECURSIVE (recursive locks). For recursive lock, the same thread of a recursive lock locked many times, there will be a counter lock, unlock, they also need to unlock the number of times to release the mutex.

3. The locking and unlocking

1 #include
2
3 int pthread_mutex_lock (pthread_mutex_t * mutex);
4 int pthread_mutex_trylock (pthread_mutex_t * mutex);
5 int pthread_mutex_unlock (pthread_mutex_t * mutex);
Parameters are mutex pointer. pthread_mutex_lock () will not lock blocking, int pthread_mutex_trylock () returns not lock immediately and return EBUSY error.

There is also a pthread_mutex_timedlock () based on the time to wait for the lock, if not this time lock will return ETIMEDOUT error!

1 #include
2 #include
3
4 int pthread_mutex_timedlock (pthread_mutex_t * restrict mutex, const struct timespec * restrict abs_timeout);
4. Destruction mutex

1 #include
2
3 int pthread_mutex_destroy (pthread_mutex_t * mutex);
mutex: Create mutex pointer

III. A simple example

Write a simple example, the main thread consumption, the production of sub-thread, and the use of simulation may be encountered during the shortcomings

1 /**
2 * @file pthread_mutex.c
3 * /
4
5 #include
6 #include
7 #include
8 #include
9 #include
10
11 / * Define the mutex * /
12 pthread_mutex_t mtx;
13 / * mutex attribute * /
14 pthread_mutexattr_t mtx_attr;
15 / * Global Resources * /
16 int money;
17
18 void err_exit (const char * err_msg)
19 {
20 printf ( "error:% s n", err_msg);
21 exit (1);
twenty two }
twenty three
24 / * thread function * /
25 void * thread_fun (void * arg)
26 {
27 while (1)
28 {
29 / * lock * /
30 pthread_mutex_lock (& mtx);
31
32 printf ( "child thread enters the critical area to see money n");
33 if (money == 0)
34 {
35 money + = 200;
36 printf ( "child thread: money =% d n", money);
37}
38
39 / * unlock * /
40 pthread_mutex_unlock (& mtx);
41
42 sleep (1);
43}
44
45 return NULL;
46}
47
48 int main (void)
49 {
50 pthread_t tid;
51
52 / * initialize the mutex attribute * /
53 if (pthread_mutexattr_init (& mtx_attr) == -1)
54 err_exit ( "pthread_mutexattr_init ()");
55
56 / * Set mutex attribute * /
57 if (pthread_mutexattr_settype (& mtx_attr, PTHREAD_MUTEX_NORMAL) == -1)
58 err_exit ( "pthread_mutexattr_settype ()");
59
60 / * initialize the mutex * /
61 if (pthread_mutex_init (& mtx, & mtx_attr) == -1)
62 err_exit ( "pthread_mutex_init ()");
63
64 / * create a thread * /
65 if (pthread_create (& tid, NULL, thread_fun, NULL) == -1)
66 err_exit ( "pthread_create ()");
67
68 money = 1000;
69 while (1)
70 {
71 / * lock * /
72 pthread_mutex_lock (& mtx);
73
74 if (money> 0)
75 {
76 money - = 100;
77 printf ( "main thread: money =% d n", money);
78}
79
80 / * unlock * /
81 pthread_mutex_unlock (& mtx);
82
83 sleep (1);
84}
85
86 return 0;
87}
The main thread and child thread of money operations were mutex protection. Line 68, the initialization money is 1000, the main thread consumes 100 each, only to money is the child thread 0 is the only production. sleep (1) to prevent the exclusive cpu, but also easy to print information.

You can see there is a huge waste of resources problem: the main thread consumes money when the child thread does not know when it was finished consumed each time the kernel scheduler to it, it will enter the critical section mutex lock, then See money, then unlock. This meaningless operation is simply a great waste! Is there any way to solve this problem? It has a good partner, called the condition variable.

IV. Deadlock

Assumptions: 1 When a thread acquires the lock 1, 2 and then acquire the lock before entering the critical region 1, thread 2 acquires the lock 2, then get a lock to enter the critical region 2. Sometime, 1 thread acquired the lock 1, 2 go to acquire the lock when the lock 2 has been found locked thread 2, and thread 2 acquires the lock 2 and found the lock 1 is locked thread 1. Thus two threads so that nobody who can not get into their critical region, creates deadlock! Usually such cases are common solution: A uniform locking order. Thread 1 and thread 2 are in accordance with the first lock 1, lock 2 again. One is also using pthread_mutex_trylock (), if the function returns EBUSY error, the release of all lock this thread, but a bit inefficient.
     
         
         
         
  More:      
 
- Android project using the command to create and install the package (Programming)
- C language header file defines a global variable (Programming)
- To install Ganglia configuration of experience under CentOS 5.5 (Linux)
- After reloading the cinder-volume OpenStack not start properly (Server)
- How do I cancel (almost) any operations in Git, (Linux)
- Custom Android UI template Comments (Programming)
- C language keywords Comments (Programming)
- Installing PHP Memcache extension under Linux (Server)
- Web server security policy (Linux)
- AppCode developed Mac OS X application or shared library experience summary (Programming)
- How to configure MongoDB replica set (Database)
- Installation of Python2.7.10 under CentOS 6.4 (Linux)
- Postgres-X2 deployment steps (Database)
- C ++ pointer two third memory model (Programming)
- Python cause yum upgrade error (Linux)
- grep command Detailed and relevant examples (Linux)
- openSUSE 13.1 / 13.2 installation SoundConverter 2.1.2 (Linux)
- Seven Steps to Help Google Chrome Speed - (Linux)
- Oracle 10g New Features - Archive Compression (Database)
- findmnt- Looking mounted file system (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.