python多线程

原文

http://www.csdn.net/article/2013-05-02/2815101

多线程主要就是线程同步的问题

比如下面的例子

import threading
TOTAL = 0
class CountThread(threading.Thread):
    def run(self):
        global TOTAL
        for i in range(100):
            TOTAL = TOTAL + 1
        print('%s
' % (TOTAL))
a = CountThread()
b = CountThread()
a.start()
b.start()

这问题是由于代码的TOTAL=TOTAL+1这行不是原子的。上下文切换切换可以刚好在这行执行的中间发生。我们需要在代码周围加上锁让它成为一个原子操作。

import threading
TOTAL = 0
MY_LOCK = threading.Lock()
class CountThread(threading.Thread):
    def run(self):
        global TOTAL
        for i in range(100000):
            MY_LOCK.acquire()
            TOTAL = TOTAL + 1
            MY_LOCK.release()
        print('%s
' % (TOTAL))
a = CountThread()
b = CountThread()
a.start()
b.start()
#coding=utf-8
import threading
from time import sleep, ctime

loops = [4, 2]

def loop(nloop, nsec):
    print "start loop", nloop, "at", ctime()
    sleep(nsec)
    print "loop", nloop, "done at", ctime()

def main():
    print "starting at", ctime()
    threads = []
    nloops = range(len(loops))

    for i in nloops:
        t = threading.Thread(target=loop, args=(i, loops[i]))
        threads.append(t)

    for i in nloops:
        threads[i].start()

    for i in nloops:
        threads[i].join()

    print "all done at", ctime()

if __name__ == "__main__":
    main()

在这个函数中,是所有的线程都创建了以后,然后一起调用start启动。

join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数,避免无休止的等待。因为两个线程顺序完成,看起来象一个线程,所以称为线程的合并。

原文地址:https://www.cnblogs.com/virusdefender/p/3574589.html