Robyn icon indicating copy to clipboard operation
Robyn copied to clipboard

Global variables changing only one time with threading

Open Peticali opened this issue 1 year ago • 5 comments

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

Peticali avatar Dec 14 '23 09:12 Peticali

Hey @Peticali 👋

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

sansyrox avatar Dec 14 '23 11:12 sansyrox

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()

meirdev avatar Dec 28 '23 07:12 meirdev

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 avatar Dec 28 '23 20:12 sansyrox

@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 avatar Jun 07 '24 14:06 sansyrox

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

sansyrox avatar Jun 09 '24 02:06 sansyrox

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

ref

VishnuSanal avatar Jul 20 '24 17:07 VishnuSanal