python 自学笔记 20151224

多线程

  • 进程是由若干现成组成的
  • 线程是操作系统直接支持的执行单元,因此,高级语言统称都内置多线程的支持
  • python的标准库提供了两个模块:_thread threading_thread是低级模块,threading是高级模块,对_thread进行了封装。在绝大多数情况下,我们通常用到threading模块。
  • 启动一个线程就是把一个函数传入并创建thread实例,然后调用start开始执行
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 ended.' % threading.current_thread().name)

print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)

执行结果为;

thread MainThread is running...
thread LoopThread is running...
thread LoopThread >>> 1
thread LoopThread >>> 2
thread LoopThread >>> 3
thread LoopThread >>> 4
thread LoopThread >>> 5
thread LoopThread ended.
thread MainThread ended.

由于任何进程都会默认启动一个线程,我们把该线程称之为主线程,主线程又可以启动新的线程。

  • python的threading模块有个current_thread函数,返回当前线程的实例
    • 主线程的实例名为mainThread,子线程的名称在创建的时候建立

lock

  • 多进程中,同一个变量,各自有一份拷贝存在每个进程中,互不影响。而在多线程中,所有的变量都由线程共享,所以任何一个变量都有可能被任何一个线层修改。
import time, threading

# 假定这是你的银行存款:
balance = 0

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
  • 为了避免变量被线程之间互相修改,避免线层之间数据共享带来的风险,引入lock
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值