Simply put, we need a mechanism to control the order of line execution.
Semaphores can provide a mechanism that only one thread is accessing a critical area at the same time (critical area refers to the program segment that accesses the resources used by * * * *), that is to say, semaphores are used to coordinate threads' access to the resources used by * * * *.
The semaphore can be understood as a resource counter, and there are two operations on the semaphore to achieve mutual exclusion, namely P and V operations. In general, critical access or mutual exclusion access is carried out as follows: let the signal value be 1, and when a thread A is running, use resources for P operation, that is, the signal value decreases 1, that is, the number of resources decreases 1. At this time, the signal amplitude is 0. It is stipulated in the system that when the signal amplitude is zero, it is necessary to wait until the signal amplitude is not zero before continuing the operation. At this point, thread B must also perform P operation to run, but the semaphore is 0 at this time, so it cannot be subtracted from 1, that is, it cannot operate P and is blocked. In this way, the exclusive access of thread A is realized. When thread A finishes running, release resources and execute V operation. When the number of resources increases by 1, the value of the semaphore becomes 1. At this time, thread B finds that the number of resources is not 0, and the semaphore can perform P operation immediately. The signal value becomes 0 again, thread B has resources, and the rest of the threads have to wait until the exclusive access of thread B is realized. This is the principle of mutual exclusion of semaphore control threads.
There are three functions in GCD that are semaphore operations, namely:
The first function has a long integer parameter, which we can understand as the total amount of signals. Dispatch_semaphore_signal is to send a signal, which will naturally add 1 to the total signal, and dispatch_semaphore_wait will wait for the signal. When the total signal amount is less than 0, it will wait all the time, otherwise it can be executed normally, and the total signal amount is-1.
Semaphores are used for multithreading concurrency. When a thread completes an action, it tells other threads through semaphores that other threads will perform some actions.
1. The difference between semaphores and locks
2. Talking about the semaphore in GCD
3. Solve the synchronization and mutual exclusion of processes with semaphores.