七日Python之路--第四天(之多线程)

时间:2022-07-22
本文章向大家介绍七日Python之路--第四天(之多线程),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

(一)程序,进程,线程

程序,为解决某特定问题而用计算机语言编写的命令序列的集合。静态,一个程序可以有多个进程。

进程,是一个具有一定独立功能的程序关于某个数据集合的一次运行活动。动态,程序的动态运行。

线程,是进程中某个单一的顺序的控制。

在单个程序中,同时运行多个线程完成不同的工作,称为多线程。

# 一段简单的代码

#!/usr/bin/python
#coding:utf-8

import time

def lop(name,times=2,sleeptime=0):
    for i in xrange(times):
        time.sleep(sleeptime)
        print '%s:%s' % (name,i)

lop('a',3)
lop('b',3)

python中,拥有众多的类库。对于线程,需要使用到Python中thread模块。

(二)线程锁

线程的运行:任意时刻只能有一个线程在执行。

thread模块:可在Python中,使用help(thread)查看帮助

#!/usr/bin/python
#coding:utf-8

import time
import thread

def lop(name,times,sleeptime,l):
    for i in xrange(times):
        time.sleep(sleeptime)
        print '%s:%s' % (name,i)
    #进行解锁
    l.release()

#生成一个线程锁
lock = thread.allocate_lock()
#进行加锁
lock.acquire()
#新建一个线程
thread.start_new_thread(lop,('a',5,0,lock))

#当线程锁处于加锁状态时,进程继续执行
while lock.locked():
    pass

注:程序代码在开始执行时,便形成了一个进程。或者说进程就是程序代码的一次动态执行过程。当执行到thread.start_new_thread()时,便新建了一个线程,然后由线程去执行lop()函数。此时进程继续执行,倘若不加线程锁,刚才新建的线程会随着该进程的结束而结束,可能会导致线程没执行完就意外终止。

thread只是Python中提供的一个对线程简单的控制。更复杂的控制需要使用,threading模块。

thread.start_new_thread(function, args[, kwargs])
    Start a new thread and return its identifier.  The thread executes the functionfunction with the argument list args (which must be a tuple).  The optionalkwargs argument specifies a dictionary of keyword arguments. When the function
    returns, the thread silently exits.  When the function terminates with an
    unhandled exception, a stack trace is printed and then the thread exits (but
    other threads continue to run).
thread.allocate_lock()
    Return a new lock object.  Methods of locks are described below.  The lock is
    initially unlocked.

lock.acquire([waitflag])
    Without the optional argument, this method acquires the lock unconditionally, if
    necessary waiting until it is released by another thread (only one thread at a
    time can acquire a lock — that’s their reason for existence).  If the integerwaitflag argument is present, the action depends on its value: if it is zero,
    the lock is only acquired if it can be acquired immediately without waiting,
    while if it is nonzero, the lock is acquired unconditionally as before.  The
    return value is True if the lock is acquired successfully, False if not.
lock.release()
    Releases the lock.  The lock must have been acquired earlier, but not
    necessarily by the same thread.
lock.locked()
    Return the status of the lock: True if it has been acquired by some thread,False if not.

关于线程的知识点比较多......Orz.

稍后再做研究,先看Django去了 ......

--2014.7.24 15:17