python模块学习---多线程处理

来源:互联网 发布:testin众测知乎 编辑:程序博客网 时间:2024/04/28 13:12

在介绍 thread 之前,先看一段代码,猜猜程序运行完成之后,在控制台上输出的结果是什么?

import thread, timecount = 0def threadTest():    global count    for i in xrange(10000):        count += 1for i in range(10):    thread.start_new_thread(threadTest, ())time.sleep(3)print count

输出结果:3018

thread.start_new_thread function args [ , kwargs ] )函数将创建一个新的线程,并返回该线程的标识符(标识符为整数)。参数 function 表示线程创建之后,立即执行的函数,参数 args 是该函数的参数,它是一个元组类型;第二个参数 kwargs 是可选的,它为函数提供了命名参数字典。函数执行完毕之后,线程将自动退出。如果函数在执行过程中遇到未处理的异常,该线程将退出,但不会影响其他线程的执行。 下面是一个简单的例子:

import thread, timedef threadFunc(a, b, c, d):    print time.strftime('%H:%M:%S', time.localtime()), a    time.sleep(1)        print time.strftime('%H:%M:%S', time.localtime()), b    time.sleep(1)    print time.strftime('%H:%M:%S', time.localtime()), c    time.sleep(1)    print time.strftime('%H:%M:%S', time.localtime()), d    time.sleep(1)    thread.start_new_thread(threadFunc, (1, 2, 3, 4))time.sleep(4)print time.strftime('%H:%M:%S', time.localtime()), 'over'

thread.exit ()结束当前线程。调用该函数会触发 SystemExit 异常,如果没有处理该异常,线程将结束。

thread.get_ident ()返回当前线程的标识符,标识符是一个非零整数。

thread.allocate_lock() #创建一个琐对象
lock.acquire ( [ waitflag ] )获取琐。函数返回一个布尔值,如果获取成功,返回 True ,否则返回 False 。参数 waitflag 的默认值是一个非零整数,表示如果琐已经被其他线程占用,那么当前线程将一直等待,只到其他线程释放,然后获取访琐。如果将参数 waitflag 置为 0 ,那么当前线程会尝试获取琐,不管琐是否被其他线程占用,当前线程都不会等待.
lock.locked()判断琐是否被占用。
lock.release()释放所占用的琐
再一次重新编写刚开始的程序,我们给线程加上锁,代码如下:

import thread, timecount = 0lock = thread.allocate_lock()def threadTest():    global count, lock    lock.acquire()        print lock.locked()        for i in xrange(1000):        count += 1        lock.release()    for i in range(10):    thread.start_new_thread(threadTest, ())time.sleep(3)print count


则运行结果:10*1000 = 10000

原创粉丝点击