Multitasking -python achieve - the concept of synchronization, a mutex to solve the resource contention (2.1.4)

@(network programming)

1. The concept of synchronization

Synchronization is coordinated pace, and operated in accordance with predetermined priorities, as you say everything I said in
synchronization with the sub-surface is easy to understand for the work
is in fact not, should be coordinated with the means to assist, cooperate with each other
such as process, thread synchronization, can be understood as processes or threads a, B with an
a run to a certain stage of relying on one of the results of B
so a stop and let B operation
results obtained by the implementation of B to a, let a continue operating

2. Solve the threads modify global variable manner

Use thread synchronization ideas

When a thread is the transfer of global variables, variables to add a lock
when a complete execution and then release the lock
does not allow other threads in the process of accessing locked in, ensures the accuracy of the data

3. mutex

When a plurality of threads simultaneously modify a shared data, the synchronization control required

The simplest synchronization mechanism is a mutex
mutex for the introduction of a resource status: locked / unlocked
mutex to ensure the correctness of the multiple threads of data

Code

import threading

g_num = 0

def test1(num):
    global g_num
    #上锁,如果之前没有被上锁,那么此时上锁成功
    #如果上锁之前 已经被上锁了,那么此时会被堵塞到这里,直到 这个锁被解开为止
    mutex.acquire()
    for i in range(num):
     g_num += 1
    #解锁
    mutex.release()
    print("in test1 gnum = %d" % g_num)

def test2(num):
    global g_num
    mutex.acquire()
    for i in range(num):
        g_num += 1
    mutex.release()

    print("in test2 gnum = %d" % g_num)

#创建一个互斥锁,默认是没有上锁的
mutex = threading.Lock()

def main():

    t1 = threading.Thread(target=test1,args=(100000000,))
    t2 = threading.Thread(target=test2,args=(100000000,))

    t1.start()
    t2.start()

if __name__ == '__main__':
    main()

note

  • Here on the outside to the process for loop, locking cycle is completed to give unlocked, the output is the first output of 100 million, 200 million in output, no doubt correct results
  • The locking and unlocking placed inside a for loop, there will be the first result and the second result appeared almost simultaneously, but the final result is correct, because in the implementation of the end of the calculation cycle test1 test2 then snatched , big calculation process is not interrupted, so the results are not affected

Guess you like

Origin www.cnblogs.com/simon-idea/p/11318352.html
Recommended