欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 多线程(小试牛刀)

程序员文章站 2024-02-23 08:09:34
...

摘要

查阅了一下资料后,发现想要在Python通过多线程来加快任务执行不太靠谱,还是使用多进程比较好,参考以下教程:

http://python.jobbole.com/82045/


使用到了join, lock, queue等基础的功能
关于GIL,业务复杂型可用MT,数据复杂型还是用MultiProcessing

import threading
import time
from queue import Queue

def thread_job():
    print("T1 start\n")
    for i in range(10):
        time.sleep(0.1)
    print("T1 finished\n")

def thread_job2():
    print("T2 start\n")
    print("T2 finished\n")

# Queue
def job(l,q):
    for i in range(len(l)):
        l[i] = l[i]**2
    q.put(l) # 不能return!

def thread_job3():
    q = Queue()
    threads = []
    data = [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]
    for i in range(4):
        t = threading.Thread(target=job, args=(data[i],q))
        t.start()
        threads.append(t)
    for thread in threads:
        thread.join()
    results = []
    for _ in range(4):
        results.append(q.get())
    print(results)

# Lock
def job1():
    global A, lock
    lock.acquire()
    for i in range(10):
        A+=1
        print("job1: ",A)
    lock.release()

def job2():
    global A, lock
    lock.acquire()
    for i in range(10):
        A+=10
        print("job2: ", A)
    lock.release()

def main_lock():
    thread1 = threading.Thread(target=job1, name='T1')
    thread2 = threading.Thread(target=job2, name='T2')
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

def main():
    thread1 = threading.Thread(target=thread_job, name='T1')
    thread2 = threading.Thread(target=thread_job2, name='T2')
    thread1.start()
    thread1.join()
    thread2.start()
    thread2.join()
    print('all done\n')
    # print("Current Activate Threading: ", threading.active_count())
    # print(threading.enumerate())
    # print(threading.current_thread())

if __name__ == '__main__':
    lock = threading.Lock()
    A = 0
    main_lock()