執行緒鎖的運用

2021-09-26 12:02:04 字數 2836 閱讀 5919

多個執行緒對同乙個資料進行修改時, 可能會出現不可預料的情況.
# 1. 例項化乙個鎖物件;

# lock = threading.lock()

# 2. 操作變數之前進行加鎖

# lock.acquire()

# 3. 操作變數之後進行解鎖

# lock.release()

import threading

# 以銀行存錢和取錢舉例

def add(lock):

global money # 生命money為全域性變數

for i in range(1000):

# 2. 操作變數之前進行加鎖

lock.acquire()

money += 1

# 3. 操作變數之後進行解鎖

lock.release()

def reduce(lock):

global money

for i in range(1000):

# 2. 操作變數之前進行加鎖

lock.acquire()

money -= 1

# 3. 操作變數之後進行解鎖

lock.release()

if __name__ == '__main__':

money=0

# 1. 例項化乙個鎖物件;

lock = threading.lock()

t1 = threading.thread(target=add, args=(lock,))

t2 = threading.thread(target=reduce, args=(lock,))

t1.start()

t2.start()

t1.join()

t2.join()

print("當前金額:", money)

# 當使用繼承來實現多執行緒

import threading

class addthread(threading.thread):

def __init__(self, lock):

super(addthread, self).__init__()

self.lock = lock

def run(self):

for i in range(1000000):

# 2. 操作變數之前進行加鎖

self.lock.acquire()

global money

money += 1 # money; money+1; money=money+1;

# 3. 操作變數之後進行解鎖

self.lock.release()

class reducethread(threading.thread):

def __init__(self, lock):

super(reducethread, self).__init__()

self.lock = lock

def run(self):

global money

for i in range(1000000):

# 2. 操作變數之前進行加鎖

lock.acquire()

money -= 1

# 3. 操作變數之後進行解鎖

lock.release()

if __name__ == '__main__':

money = 0

# 1. 例項化乙個鎖物件;

lock = threading.lock()

t1 = addthread(lock)

t2 = reducethread(lock)

t1.start()

t2.start()

t1.join()

t2.join()

print("當前金額:", money)

import threading

from urllib.request import urlopen

download_dir = 'doc'

class downloadthread(threading.thread):

def __init__(self, url):

super(downloadthread, self).__init__()

self.url = url

def run(self):

try:

urlobj = urlopen(self.url)

except exception as e:

print("download %s error\n" % (self.url), e)

imgcontent = none

else:

filename = self.url.split("/")[-1]

# 'ab'

with open("%s/%s" % (download_dir, filename), 'ab') as f:

while true:

imgcontentchunk = urlobj.read(1024 * 3)

if not imgcontentchunk:

break

f.write(imgcontentchunk)

url1=''

url2=''

urls = [url1,url2]

for url in urls:

thread = downloadthread(url)

thread.start()

thread.join()

多執行緒的運用 鎖

import threading import time import random defreading for i in range 5 print 執行緒reading i time.sleep random.randint 1,2 def writing for i in range 5 p...

執行緒中鎖的運用及遇到的問題

需求 無限迴圈交替列印出 張三,女 zhangsan,famle 定義兩個執行緒。注意同步的條件 1.至少有兩個執行緒在對同一資源進行操作。2.具有相同的鎖。同步函式的鎖是this,靜態函式的鎖是類.classclass resource class input implements runnabl...

讀寫鎖的簡單運用

與互斥鎖定相比,讀 寫鎖定允許對共享資料進行更高階別的併發訪問。雖然一次只有乙個執行緒 writer 執行緒 可以修改共享資料,但在許多情況下,任何數量的執行緒可以同時讀取共享資料 reader 執行緒 讀 寫鎖定利用了這一點。從理論上講,與互斥鎖定相比,使用讀 寫鎖定所允許的併發性增強將帶來更大的...