Multitasking -python implementation - multi-threaded shared global variables (2.1.3)

@(network programming)

1. Modify global variables

Code

num = 100
nums = [11,22]

def test():
    global num

    num += 100

def  test2():
    nums.append(33)

print(num)
print(nums)

test()
test2()

print(num)
print(nums)

Output:
200
[11, 22, 33]

note

  • num used in the function must first use globel modification, and nums is an array, a list append method used in the function, the list does not change the original point so you can not use global
  • So if you want to re-assign the type of data (= number), then to use the global modified look, then do not re-assigned

2. Global variables shared in a multi-thread

Code

import threading

g_num = 100

def test1():
    global g_num
    g_num += 1
    print("in test1 gnum = %d" % g_num)

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


def main():
    t1 = threading.Thread(target=test1())
    t2 = threading.Thread(target=test2())

    t1.start()
    t2.start()

if __name__ == '__main__':
    main()

输出,
a sign test1 = 101
in the rapidly test2 = 101

note

  • We can see two threads of equal value
  • This is because when using global variables of the global lock, and only released after completing +

3. multithreading problems that may be encountered

Suppose that two threads t1 and t2 need to make more global variables g_nums (default 0) +1 operations, t1 and t2 are the team g_num plus 10 times
the final result should be 20, but the problem may occur due to the multithreading problem
Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/simon-idea/p/11317933.html