Locking by string. Is this safe/sane?

前端 未结 9 1632
-上瘾入骨i
-上瘾入骨i 2020-12-14 01:33

I need to lock a section of code by string. Of course the following code is hideously unsafe:

lock(\"http://someurl\")
{
    //bla
}

So I\'

9条回答
  •  -上瘾入骨i
    2020-12-14 01:57

    In most cases, when you think you need locks, you don't. Instead, try to use thread-safe data structure (e.g. Queue) which handles the locking for you.

    For example, in python:

    class RequestManager(Thread):
        def __init__(self):
            super().__init__()
            self.requests = Queue()
            self.cache = dict()
        def run(self):        
            while True:
                url, q = self.requests.get()
                if url not in self.cache:
                    self.cache[url] = urlopen(url).read()[:100]
                q.put(self.cache[url])
    
        # get() runs on MyThread's thread, not RequestManager's
        def get(self, url):
            q = Queue(1)
            self.requests.put((url, q))
            return q.get()
    
    class MyThread(Thread):
        def __init__(self):
            super().__init__()
        def run(self):
            while True:
                sleep(random())
                url = ['http://www.google.com/', 'http://www.yahoo.com', 'http://www.microsoft.com'][randrange(0, 3)]
                img = rm.get(url)
                print(img)
    

提交回复
热议问题