Python使用threading.Event()

时间:2014-08-26 14:44:21

标签: python multithreading event-handling

我有两个访问Web服务的线程。一个线程正在更新资源,另一个线程可能正在获取它们。

我的webservice类如下所示:

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

我想确保在访问get之前调用update。我正在使用threading.Event()来同步update()和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()

但不知何故,当我有两个线程update()和get()时,update()事务成功但get()没有返回,它停留在那里等待。

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!!"

我做错了吗?

0 个答案:

没有答案