The operating system processes and threads 4

Process-Thread - Synchronization

  • Maskable interrupt

    • Single processor, the easiest way is to enter the critical area immediately after the mask all interrupts, then turn left interrupted, the masked interrupt clock interrupts are masked, cpu will not carry out the process of switching.
    • This way many disadvantages, if not break open, multi-processor interrupt mask instructions to only one other entry into force of cpu cpu can still enter the critical region, and therefore not applicable.
  • Busy wait algorithm

    • Here are three competing means locking are busy with other needs. When they did not get the lock and enter the critical region need to wait for the cycle has been in place, such a waste of CPU time, priority inversion problem may also occur.

    • Priority inversion problem : suppose there is a priority among threads, as long as a higher priority thread is in the ready state has been run without surrender cpu. Low priority thread because if at some time a low-priority thread is in the critical region and perform free operations such as high-priority thread is cpu, in which case a higher priority thread as busy and so will not surrender cpu, and can not cpu to get done performing operations critical area so you can not hand over the lock, thus causing a deadlock.

    • Strict rotation algorithm

      • Strict rotation algorithm can control two threads access a shared resource single user without access violation occurs. But there are strict rotation order of execution.

        int turn=0;//运行权限的线程id
        void enter(int process){
            //如果turn不为当前线程则一直循环等待
            while(turn != process);
        }
        void leave(int process){
            //将运行权限交给另一个线程
            turn = 1-process;
        }
        
      • Strict rotation algorithm has a significant drawback is a thread to get the resources and authority after use will leave to another thread while another thread if there is no access to this resource and use after the completion of this thread can not leave once again, access to resources.

      • Therefore, access to resources in strict rotation order algorithm must be strictly followed this sequence 0-1-0-1 obtained.

    • Peterson's algorithm

      • Peterson's algorithm is an implementation of mutex concurrent programming algorithm that can control two threads single-user access to a shared resource without access violation occurs.

      • And compared to the strict rotation algorithm it avoids some extent after leaving a thread access to resources and access to resources had to wait another thread and leave to get to the disadvantage of resources. For on-demand competition - only one thread will own the competition flag will be set up in another thread will wait for it.

        #define TRUE  1
        #define FALSE 0
        int turn;  		//当前有权限的线程id
        int flag[2];	//是否竞争标志位
        void enter(int porcess){
            int other = 1 - process; //另一个线程号
            interested[process] = TRUE; //当前开始了竞争
            turn = other; //权限给对方线程
            //如果当前线程没有权限且对方的竞争标志位为true则等待。
            while(turn != process && flag[other] == TRUE);
        }
        void leave(int process){
            inserested[process] = FASLE;//取消了竞争
        }
        
      • It can be seen only by the code

        • 1 the other thread is not set to true competition in their own flag
        • 2 When the other thread executes turn = other when the rights to this thread
        • After 3 other threads to obtain the resources when the resource will leave their competitive flag is set to false
        • This is only one of three cases can be obtained to meet the resource rather than waiting for the cycle.
      • T0 execution, T2 has not been executed

        T0 T1
        flag[0]=true No execution
        turn=1 No execution
        They did not enter the circulation, access to resources No execution
      • When executed T0, T1 also performed

        T0 into circulation before the judge, T1 will mark their competitive position is true, resulting in cycle T0 has been performed to wait until T1 permission to turn = 0 at T0, T0 before the end of the cycle to get the resources.

        T0 T1
        flag[0]=true flag[1]=true
        turn=1 No execution
        Do not wait for permission to cycle No execution
        Do not wait for permission to cycle turn=0
        Obtaining permission, the end of the cycle to obtain resources Do not wait for permission to cycle
        flag [0] = false competition canceled Do not wait for permission to cycle
        No execution The other party to cancel the competition, ending the cycle to obtain resources
    • TSL instruction and XCHG

      • TSL and XCHG provide atomic read and updated features, use these instructions can easily achieve multi-threaded competition program lock function.

      • The TSL (test and lock instruction), the TSL RX, LOCK, LOCK it a memory word address registers RX, read, and a non-zero value stored in the memory address. Read and write is guaranteed atomic. Implementation of the directive will lock the CPU memory bus to prohibit other cpu to access this address.

        enter_region:
        	;复制LOCK地址存的值到REGISTER寄存器上
        	;并将LOCK地址的值设置为1
        	TSL REGISTER,LOCK 
        	CMP REGISTER,#0  ;判断取出的值是否为0
        	JNE enter_region ;不是0则代表锁已被占有,继续循环
        	RET ;获得到了锁,返回调用者
        leave_region:
        	MOVE LOCK,#0 ;向LOCK地址存入0
        	RET          ;返回调用者
        
      • XCHG (atomic swap instruction), the memory word XCHG RX, LOCK, will address the RX LOCK register words are exchanged. It may be used instead TSL, are all Intel x86 instruction XCHG underlying synchronization used.

        enter_region:
        	MOVE REGISTER,#1   ;寄存器中放个1
        	XCHG REGISTER,LOCK ;交换LOCK与寄存器的数值
        	CMP REGISTER,#0    ;判断LOCK之前存的是否为0
        	JNE enter_region   ;不是0则说明锁已经设置,循环等待
        	RET ;获得了锁,返回调用者
        leave_region:
        	MOVE LOCK,#0  ;在LOCK处存入0
        	RET           ;返回调用者
        
  • Wake achieve thread blocks busy, etc.

    • sleep and wakeup call systems, can thread into the lock when you can not get blocked, instead of waiting for busy cpu, cpu avoid the waste of resources.

    • signal

      • Semaphore is by an integer variable to the cumulative number of wake. Divided up and down operation.
      • down operation of the semaphore> 0 of the signal minus a semaphore = 0, the thread is sleeping.
      • up operations in the amount of signal when no thread to sleep plus a semaphore, or random wake up a thread.
      • Note: For the semaphore operation variables must be atomic.
    • Mutex

      • If no counting semaphore functions, you can use a simplified version thereof - mutex.

      • Mutex lock and unlock divided into two operations, only one bit can be expressed.

      • If you call a lock, if another thread has acquired the lock of the thread is blocked.

      • Thread acquires the lock when you unlock randomly because they can not wake up a locked and blocked thread.

        ;一种用户级线程的解决方案
        mutex_lock:
        	TSL REGISTER,MUTEX ;互斥量复制到寄存器中,互斥量置1
        	CMP REGISTER,#0 ;判断复制出来的互斥量是否为0
        	JZE ok ;是0则获得了锁直接结束
        	CALL thread_yield ;不是0则让出cpu资源
        	JMP mutex_lock ;阻塞恢复后回到开始重新尝试加锁
        ok: RET
        
        mutex_unlock:
        	MOVE MUTEX,#0 ;将互斥量值0
        	RET
        
    • The synchronization function provided pthread

      • Pthread provides two synchronization mechanisms: mutex, condition variables.

      • Mutex

        • Mutex (mutex) at the same time only one thread can be obtained, while other threads failed attempt to get blocks until the mutex is unlocked other threads.

        • It provides a series of calls

          Thread calls description
          pthread_mutex_init Creating a mutex
          pthread_mutex_destory Revocation of a mutex
          pthread_mutex_lock Obtain a mutex or obstruction
          pthread_mutex_trylock Or failure to obtain a mutex
          pthread_mutex_unlock Release mutex
      • Condition variable

        • When the condition variable allows a thread to a number of conditions have not been met because of blocked until another thread to do the work so that the conditions are met to wake blocked threads.

        • It provides a series of calls

        Thread calls description
        pthread_cond_init Create a condition variable
        pthread_cond_destory Revocation of a condition variable
        pthread_cond_wait Blocks waiting for a signal
        pthread_cond_signal Wake it sends a signal to another thread
        pthread_cond_broadcast They wake up multiple threads to send signals to the
        • pthread_cond_wait passing a mutex mutex function, when you call it releases atomic unlock the mutex, and to this thread added to the waiting queue, when it will wake cause the function to return again fighting to get the mutex lock.
      • Examples of conditions for use with variable mutex

        #include<pthread.h>
        int value=0;
        pthread_mutex_t mutex;
        pthread_cond_t cond;
        void provider(){
            lock(&mutex);
        	while(value<=0){
        		pthread_cond_wait(&cond,&mutex);
        	}
        	unlock(&mutex);
        }
        void consumer(){
            lock(&mutex);
        	if(value==0){
        		value++;
        	}
        	if(value>0){
        		pthread_cond_signal(&cond);
        	}
        	unlock(&mutex);
        }
        
      • Condition variable is resolved in some cases we need to wait when conditions are met, if only you'll need to lock mutex and then determine whether the conditions are met, if not meet the need to release the lock and lock sleep or repeat judgment. The cycle has been caused by waste cpu, sleep and because recycled wait condition is satisfied and therefore unable to determine sleep time sleep time may be too long.

      • So take advantage of in this case with a condition variable waiting queue with notices wake mode becomes more robust performance, and when the conditions are not met it will be added to the waiting queue thread, and the work of other threads can cause the conditions are met wake up a thread waiting in the queue. This will not only avoid the cycle lock judgment brought cpu waste and avoid the disadvantages of long sleep time.

Published 27 original articles · won praise 1 · views 892

Guess you like

Origin blog.csdn.net/hu853996234/article/details/105026004