问题
I have two threads that are accessing a web service. One thread is updating a resource and other is possibly getting them.
My webservice class looks below:
class WebServiceHandler(object):
RESOURCE_URL='/Resource/{0}'
def __init__(self, host, port):
self._http_connection = httplib.HTTPSConnection(host, port)
def update(self, id, resource):
url = self.RESOURCE_URL.format(id)
self._http_connection.request('POST', url,
resource)
response = self._http_connection.getresponse()
response_body = response.read()
def get(self, id):
url = self.RESOURCE_URL.format(id)
self._http_connection.request('GET', url)
response = self._http_connection.getresponse()
response_body = response.read()
return response_body
I want to make sure before get is accessed, update is called.I was using threading.Event() to synchronize inside update() and get().
class WebServiceHandler(object):
RESOURCE_URL='/Resource/{0}'
def __init__(self, host, port):
self._http_connection = httplib.HTTPSConnection(host, port)
self._update_event = threading.Event()
def update(id, resource):
url = self.RESOURCE_URL.format(id)
self._http_connection.request('POST', url,
resource)
response = self._http_connection.getresponse()
response_body = response.read()
self._update_event.set()
def get(id):
self._update_event.wait()
self._update_event.clear()
url = self.RESOURCE_URL.format(id)
self._http_connection.request('GET', url)
response = self._http_connection.getresponse()
response_body = response.read()
But somehow when I have two thread update() and get(), update() transaction is successful but get() does not return, it stuck there waiting.
test1 = WebServiceHandler('localhost', 80)
import time
def step1():
time.sleep(4)
test1.update('10', {'resource_name': 'chef agent' })
print "updated!!"
def step2():
print test1.get('10')
thread1 = threading.Thread(target=step1)
thread2 = threading.Thread(target=step2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print "Done!!"
Am I doing something wrong?
来源:https://stackoverflow.com/questions/25508719/python-using-threading-event