Skip to content

Commit

Permalink
prevent race conditions with thread start
Browse files Browse the repository at this point in the history
Fixes #493
  • Loading branch information
miguelgrinberg committed Aug 14, 2017
1 parent 61c179d commit 5c7d14b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
7 changes: 5 additions & 2 deletions example/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
from threading import Lock
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
Expand All @@ -12,6 +13,7 @@
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()


def background_thread():
Expand Down Expand Up @@ -96,8 +98,9 @@ def ping_pong():
@socketio.on('connect', namespace='/test')
def test_connect():
global thread
if thread is None:
thread = socketio.start_background_task(target=background_thread)
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})


Expand Down
8 changes: 6 additions & 2 deletions example/app_namespace.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
from threading import Lock
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, Namespace, emit, join_room, leave_room, \
close_room, rooms, disconnect
Expand All @@ -12,6 +13,7 @@
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()


def background_thread():
Expand Down Expand Up @@ -80,8 +82,10 @@ def on_my_ping(self):

def on_connect(self):
global thread
if thread is None:
thread = socketio.start_background_task(target=background_thread)
with thread_lock:
if thread is None:
thread = socketio.start_background_task(
target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})

def on_disconnect(self):
Expand Down
Empty file modified example/sessions.py
100644 → 100755
Empty file.

0 comments on commit 5c7d14b

Please sign in to comment.