Python多线程编程

来源:互联网 发布:三维软件 编辑:程序博客网 时间:2024/06/05 00:24

使用线程有两种方法,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行。

# -*- coding: utf-8 -*-import threadingimport timeimport randomcount = 0mutex = threading.Lock()def thread_main(i):    global count, mutex    thread_name = threading.currentThread().getName()    for x in xrange(0, int(i)):        mutex.acquire()        count += 1        print thread_name, x, count        mutex.release()        time.sleep(random.randint(1, 3))def main(num):    global count, mutex    threads = []    for x in xrange(0, num):        threads.append(threading.Thread(target=thread_main, args=(3, ))) # loop 3 rounds    for t in threads:        t.start()    for t in threads:        t.join()if __name__ == '__main__':    main(4) # create 4 threads

输出:

Thread-1 0 1Thread-2 0 2Thread-3 0 3Thread-4 0 4Thread-1 1 5Thread-2 1 6Thread-3 1 7Thread-4 1 8Thread-1 2 9Thread-4 2 10Thread-3 2 11Thread-2 2 12

第二种方法是直接从Thread继承,创建一个新的类,把线程执行的代码放到这个新类里。

# -*- coding: utf-8 -*-import threadingimport timeimport randomclass Test(threading.Thread):    def __init__(self, num):        threading.Thread.__init__(self)        self.run_num = num    def run(self):        global count, mutex        thread_name = threading.currentThread().getName()        for x in xrange(0, int(self.run_num)):            mutex.acquire()            count += 1            print thread_name, x, count            mutex.release()            time.sleep(random.randint(1, 3))if __name__ == '__main__':    global count, mutex    threads = []    count = 0    mutex = threading.Lock()    for t in xrange(0, 4):  # create 4 threads        threads.append(Test(3))  # loop 3 rounds    for t in threads:        t.start()    for t in threads:        t.join()

输出:

Thread-1 0 1Thread-2 0 2Thread-3 0 3Thread-4 0 4Thread-1 1 5Thread-2 1 6Thread-4 1 7Thread-3 1 8Thread-1 2 9Thread-2 2 10Thread-3 2 11Thread-4 2 12
0 0
原创粉丝点击