Skip to content

Instantly share code, notes, and snippets.

@cdpath
Last active January 15, 2018 09:00
Show Gist options
  • Select an option

  • Save cdpath/3771db3cde75b362cf2522f677e828f6 to your computer and use it in GitHub Desktop.

Select an option

Save cdpath/3771db3cde75b362cf2522f677e828f6 to your computer and use it in GitHub Desktop.
Python threading with Exception catching
#!/usr/bin/python
# -*- coding: utf-8 -*-
from time import sleep
import sys
import threading
import Queue
ERROR_OCCURRED = object()
def test_thread():
q = Queue.Queue(maxsize=3)
t_get_items = threading.Thread(
target=get_items,
args=(q, 2),
)
t_get_items.start()
q_result = Queue.Queue(maxsize=3)
t_read_items = threading.Thread(
target=read_items,
args=(q, q_result, 6),
)
t_read_items.start()
while True:
msg = q_result.get()
# print msg
if msg is ERROR_OCCURRED:
print "Got ERROR object"
raise ValueError('Not 6!')
if msg is None:
break
t_get_items.join()
t_read_items.join()
def get_items(q, division):
items = range(100)
items = [item for item in items if item // division]
for item in items:
q.put(item)
q.put(None)
def read_items(q, q_result, division):
while True:
msg = q.get()
if msg is None:
q_result.put(None)
break
item = msg
print item
try:
print_item(q_result, item)
except ValueError:
q_result.put(ERROR_OCCURRED)
break
def print_item(q, item):
if item == 6:
print "Got 6"
raise ValueError('Not 6!')
else:
q.put(item)
def main():
count = 0
while True:
try:
some_thread()
except Exception:
print ("Error Occurred, try again (%d)" % count)
count += 1
sleep(1)
if __name__ == "__main__":
test_thread()
print("Finished")
@cdpath
Copy link
Author

cdpath commented Jan 15, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment