For an assignment, I'm supposed to create a simple multi-threaded program that has three threads that wait for a random amount of time (between.1 and 2 seconds) and then print "end." I'm trying to use locks to prevent switching from messing up the output, but my output is still seemingly random (meaning the locks aren't working as intended). My code is:
import time
from threading import *
import random
lock = Lock()
def one():
global lock
time.sleep((random.randint(1,20))/10)
lock.acquire()
print("1. end")
lock.release()
def two():
global lock
time.sleep((random.randint(1,20))/10)
lock.acquire()
print("2. end")
lock.release()
def three():
global lock
time.sleep((random.randint(1,20))/10)
lock.acquire()
print("3. end")
lock.release()
for i in range(0,100):
t1 = Thread(target = one)
t2 = Thread(target = two)
t3 = Thread(target = three)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
but my output is:
2. end
3. end
1. end
3. end
2. end
2. end
1. end
3. end
1. end
etc...
what am I doing wrong?
You acquire the lock after random sleep:
import time
from threading import *
import random
lock = Lock()
def one():
global lock
lock.acquire()
time.sleep((random.randint(1,20))/10)
print("1. end")
lock.release()
def two():
global lock
lock.acquire()
time.sleep((random.randint(1,20))/10)
print("2. end")
lock.release()
def three():
global lock
lock.acquire()
time.sleep((random.randint(1,20))/10)
print("3. end")
lock.release()
for i in range(0,100):
t1 = Thread(target = one)
t2 = Thread(target = two)
t3 = Thread(target = three)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.