can't access global variable value
pulord opened this issue · 3 comments
In Handler, I can't access the right value of global varibale
from japronto import Application
import threading
import time
global_count = 0
def get(request):
print(request)
print("hello", global_count, id(global_count))
return request.Response(text=str(global_count))
def add(request):
global global_count
global_count += 1
print("add", global_count, id(global_count))
return request.Response(text=str(global_count))
def change_thread():
while True:
global global_count
global_count += 1
print("change_thread", global_count, id(global_count))
time.sleep(1)
def print_global():
while True:
global global_count
print("print_thread", global_count, id(global_count))
time.sleep(2)
def start_http_server(port, registry):
app = Application()
app.router.add_route('/get', get)
app.router.add_route('/add', add)
app.run(debug=True, port=port)
changeThread = threading.Thread(target=change_thread, args=())
changeThread.start()
printThread = threading.Thread(target=print_global, args=())
printThread.start()
start_http_server(12001, None)
- changeThread add 1 for every secconds
- printThread print global_count for every two seconds
- we can access right global variable value in printThread
➜ tmp git:(master) ✗ python3 japronto_test.py
change_thread 1 4496121920
print_thread 1 4496121920
Accepting connections on http://0.0.0.0:12001
change_thread 2 4496121952
print_thread 2 4496121952
change_thread 3 4496121984
change_thread 4 4496122016
print_thread 4 4496122016
change_thread 5 4496122048
change_thread 6 4496122080
print_thread 6 4496122080
change_thread 7 4496122112
use handler
➜ tmp git:(master) ✗ curl http://localhost:12001/get
1
➜ tmp git:(master) ✗ curl http://localhost:12001/get
1
➜ tmp git:(master) ✗ curl http://localhost:12001/get
1
➜ tmp git:(master) ✗ curl http://localhost:12001/add
2
➜ tmp git:(master) ✗ curl http://localhost:12001/get
2
- http://localhost:12001/get always get this init value = 1
- http://localhost:12001/add can change the global value
- after add handler, get handler can get the right global variable value
But the get handler can't get changed variable value after changeThread call
Best Regards !
I try to use flask, flask works perfect!
Japronto is a forking server. Your threads work in master process while your request workers are spawned when run() is called, the memory is copied.
If you really wanted this to work you would need to start threads post fork and limit everything to 1 worker but this is a bad design for a real world apps.
Japronto is a forking server. Your threads work in master process while your request workers are spawned when run() is called, the memory is copied.
If you really wanted this to work you would need to start threads post fork and limit everything to 1 worker but this is a bad design for a real world apps.
Thanks For your replay