Skip to content
Advertisement

Is there a way to have threads communicate with each other?

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

Import time
Import threading
s=0

def thing1():
        time.sleep(1)
        s+=1
def thing2():
        print(s)

t = threading.Thread(target = thing1)
t.start()
t2 = threading.Thread(target = thing2)
t2.start()

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.

import threading
import time
s = 0
sem = threading.Semaphore()

def thing1():
    global s
    for _ in range(3):
        time.sleep(1)
        sem.acquire()
        s += 1
        sem.release()

def thing2():
    global s
    for _ in range(3):
        time.sleep(1)
        sem.acquire()
        print(s)
        sem.release()

t = threading.Thread(target = thing1)
t.start()
t2 = threading.Thread(target = thing2)
t2.start()

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement