标签:全局 import exception [1] ## png exce mos last
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
In [1]: import threading In [2]: threading.current_thread() Out[2]: <_MainThread(MainThread, started 139965328148224)> In [3]: threading.current_thread().name Out[3]: ‘MainThread‘
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()
标签:全局 import exception [1] ## png exce mos last
原文地址:http://www.cnblogs.com/venicid/p/7966836.html