Robyn
Robyn copied to clipboard
Global variables changing only one time with threading
Bug Description
The count global variable only increases in value once (1), while it should increase infinitely.
Steps to Reproduce
Example:
from robyn import Robyn
from robyn.robyn import Request, Response
import time, threading
app = Robyn(__file__)
count = 0
def Counter():
global count
while 1:
count += 1
time.sleep(0.2)
print(count,"added 1")
@app.get("/")
def Teste(r:Request):
global count
return Response(description=str(count),status_code=200,headers={})
threading.Thread(target=Counter,daemon=True).start()
app.start()
Your operating system
MacOS
Your Python version (python --version)
3.11
Your Robyn version
Other (specify below)
Additional Info
Robyn 0.45.0
Hey @Peticali 👋
Thank you for reporting this. I am having a look at this.
This is because the server uses multiprocessing, in each new process the count variable is different.
This can be solved by using multiprocessing.Value:
import threading
import time
from multiprocessing import Value
from robyn import Robyn
from robyn.robyn import Request
app = Robyn(__file__)
count = Value("i", 0)
def counter():
while True:
count.value += 1
time.sleep(0.2)
print(count.value, "added 1")
@app.get("/")
def index(request: Request):
return f"{count.value}"
threading.Thread(target=counter, daemon=True).start()
app.start()
Thank you for pinpointing the issue @meirdev 😄 This is really helpful.
I should be adding proper documentation to point this out. And maybe even define a different behaviour when processes = 1
@meirdev @Peticali , the server should behave properly if there is a single process. I shall test this again. But a recent PR should’ve fixed it.
@meirdev @Peticali , this has been fixed now. For default behaviour(single process), it works as expected. Need to add some documentation now :D
note to self:
- create a new api ref page
- doc about the value race condition & necessary protection to be done from the programmer's part