Hi I am trying to make it so 2 threads will change the other one but I can’t figure it out this is an example of what I have
JavaScript
x
15
15
1
Import time
2
Import threading
3
s=0
4
5
def thing1():
6
time.sleep(1)
7
s+=1
8
def thing2():
9
print(s)
10
11
t = threading.Thread(target = thing1)
12
t.start()
13
t2 = threading.Thread(target = thing2)
14
t2.start()
15
When they run thing2 will print 0, not the seconds. I have it so they run later this is just all the code that’s necessary
Advertisement
Answer
You need to use a semaphore so that each thread is not accessing the variable at the same time. However, any two threads can access the same variable s
using global
.
JavaScript
1
26
26
1
import threading
2
import time
3
s = 0
4
sem = threading.Semaphore()
5
6
def thing1():
7
global s
8
for _ in range(3):
9
time.sleep(1)
10
sem.acquire()
11
s += 1
12
sem.release()
13
14
def thing2():
15
global s
16
for _ in range(3):
17
time.sleep(1)
18
sem.acquire()
19
print(s)
20
sem.release()
21
22
t = threading.Thread(target = thing1)
23
t.start()
24
t2 = threading.Thread(target = thing2)
25
t2.start()
26