sparckles / Robyn

Robyn is a Super Fast Async Python Web Framework with a Rust runtime.
https://robyn.tech/
BSD 2-Clause "Simplified" License
4.3k stars 221 forks source link

Global variables changing only one time with threading #716

Closed Peticali closed 2 months ago

Peticali commented 9 months ago

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

sansyrox commented 9 months ago

Hey @Peticali 👋

Thank you for reporting this. I am having a look at this.

meirdev commented 9 months ago

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()
sansyrox commented 9 months ago

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

sansyrox commented 4 months ago

@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.

sansyrox commented 3 months ago

@meirdev @Peticali , this has been fixed now. For default behaviour(single process), it works as expected. Need to add some documentation now :D

VishnuSanal commented 2 months ago

note to self:

ref