python多線程基本用法

python是假的多線程(只是輪流進行而已),

它不適於cpu計算密集型的操作(這樣反而會變慢),

但適用於 I/O密集型的操作,(網絡請求,文件讀取)----很適用於網絡爬取.

import threading

#多線程的實現方法:
    #實現方法1:
def function():
    for i in range(10):
        print(i)
t1=threading.Thread(target=function)
t2=threading.Thread(target=function)
t1.start()
t2.start()
    #實現方法2:類似java
class MyThread(threading.Thread):
    def run(self):
        for i in range(10):
            print(i,threading.current_thread())
MyThread().start()


#線程數量
num=threading.enumerate()
print("啊",num,"啊")


#顯示當前線程:
print(threading.current_thread())


print("--------------------------------------------------------")
#全局變量:
#多線程在一個進程裏面,所以進程中的全局變量在進程種都可以使用
Value=0
def add():
    global Value
    for x in range(100):
        Value += 1
        print(Value)
for i in  range(2):
    t=threading.Thread(target=add)
    t.start()


#鎖機制:
#把所有涉及到對公共資源修改的操作都加上鎖
lock=threading.Lock()
def add():
    global Value
    lock.acquire()
    for x in range(100):
        Value += 1
        print(Value)
    lock.release()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章