9 多线程对非共享数据

1.g_num 不是全局变量

from threading import Thread
import time

def test1():
    g_num = 100
    g_num += 1
    print("---1test1--g_num=%d"%g_num)
    time.sleep(2)

def test2():
    time.sleep(1)
    print("---2test2--g_num=%d"%g_num)


t1 = Thread(target=test1)
t1.start()

t2 = Thread(target=test2)
t2.start()
### 结果
---1test1--g_num=101
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "10-多线程-非共享数据.py", line 12, in test2
    print("---2test2--g_num=%d"%g_num)
NameError: name 'g_num' is not defined

2.线程名

In [1]: import threading


In [2]: threading.current_thread()
Out[2]: <_MainThread(MainThread, started 139965328148224)>

In [3]: threading.current_thread().name
Out[3]: 'MainThread'

3.两个线程执行同一个函数

  • 两个线程执行的函数没有关系  
  • 函数个人是个人的,函数里面的变量没有关系
from threading import Thread
import threading
import time

def test1():
    name = threading.current_thread().name
    print("---the thread is %s--"%name)
    g_num = 100
    if name == "Thread-1":
        g_num += 1
        print("---%s--g_num=%d"%(name,g_num))
    else:
        time.sleep(2)
        print("----%s--g_num=%d"%(name,g_num))


t1 = Thread(target=test1)
t1.start()

t2 = Thread(target=test1)
t2.start()

    

       

小总结

  • 在多线程开发中,全局变量是多个线程都共享的数据,而局部变量等是各自线程的,是非共享的
原文地址:https://www.cnblogs.com/venicid/p/7966836.html