Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/QWERTY1994/article/details/81903994
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/20 17:32
# @Author :
# 多线程 有两个库_thread和threading,_thread是低级模块,threading是高级模块,对_thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。
import time, threading
# 新线程执行的代码
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s ' % (threading.current_thread().name, n))
time.sleep(1)
print('thread %s done...' % threading.current_thread().name)
if __name__ == '__main__':
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('Thread %s ended.' % threading.current_thread().name)
#
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/20 17:37
# @Author :
# 多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,
# 所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在
# 于多个线程同时改一个变量,把内容给改乱了。
import threading
import random
import time
blance = 0
lock = threading.Lock() # 锁
def run_thread1(n):
for i in range(10):
# 先获取锁
chang_it(n)
def run_thread2(n):
for i in range(10):
# 先获取锁
lock.acquire()
try:
# 放心改变值
chang_it(i)
finally:
lock.release() # 释放锁
def chang_it(n):
global blance
blance = blance + n
time.sleep(random.random())
blance = blance - 10
blance = blance - n
time.sleep(random.random())
blance = blance + 10
if __name__ == "__main__":
t1 = threading.Thread(target=run_thread1,args=(4,))
t2 = threading.Thread(target=run_thread1,args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(blance)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/21 10:52
# @Author :
# threadLocal
import threading
localConnection = threading.local()
def thread_running(connectio):
localConnection.connection = connectio
insertStu(connectio)
def insertStu(connection):
print("插入学生 调用连接 %s" % connection)
# 在数据库中 当前线程都有一个数据库连接 当发生错误的时候可以回滚
if __name__ == '__main__':
t1 = threading.Thread(target=thread_running, args=('连接一',))
t2 = threading.Thread(target=thread_running, args=('连接二',))
t1.start()
t2.start()
t1.join()
t2.join()
print("所有学生都已经插入")