本部门练习Python多线程操作,Python中得多线程虽然为真正得POSIX 多线程,但是由于全局进程锁GIL得存在,在计算密集型业务中,并不能发挥真正并发的作用。
Python中的多线程主要通过threading模块实现,结果操作与Java多线程和Python多进程类似。
# 多线程练习
import threading
def thread_run(text):
print("Thread [%s] is running...text:[%s]" % (threading.current_thread().name, text))
print("Main thread name: %s" % threading.current_thread().name)
for i in range(4):
t = threading.Thread(target=thread_run, args=(i,))
t.start()
t.join()
# 多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,所有变量都由所有线程共享,
# 所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了。
# 假定这是你的银行存款:
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(2000000):
change_it(n)