Python using threading.Event()

一笑奈何 提交于 2021-01-29 03:35:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!