views:

77

answers:

2

I have code that looks like something like this:

def startSearching(self):
    self.searchingLock.acquire()
    searching = self.searching
    if self.searching:
        self.searchingLock.release()
        self.logger.error("Already searching!")
        return False

    self.searching = True
    self.searchingLock.release()

    #some more init code, then start the thread which
    #constantly checks self.searching to determine when to stop

it's kind of ugly, though. lots of acquires and releases. this looks prettier:

def startSearching(self):
    with self.searchingLock:
        if self.searching:
            self.logger.error("Already searching!")
            return False

        self.searching = True

    #some more init code, then start the thread which
    #constantly checks self.searching to determine when to stop

but this keeps the lock longer than strictly necessary, espcially if self.logger.error takes a while (like if it writes to disk, which it does). is there any middle ground between holding the lock as little as possible but having prettier code?

+1  A: 

This will save you one "self.searchingLock.release()" Guess it's not very pythonic or anything but it does the job

def startSearching(self):
    self.searchingLock.acquire()
    already_searching = self.searching
    self.searching = True # Since it'll be true in both scenarios 
    self.searchingLock.release()

    if already_searching:
        self.logger.error("Already searching!")

    return not already_searching
getekha
heh clever =) i like it
Claudiu
You could even easily break the first 4 lines into another function.
+3  A: 

Maybe you need to separate this logic like:

def initSearch(self):
    with self.searchingLock:
        if self.searching : raise SearchingError('AlreadySearching')
        self.searching = True
def startSearching(self):
    try: self.initSearch()
    except SearchingError as error :
        self.logger.error(error.message)
        return False
    #some more init code, then start the thread which
    #constantly checks self.searching to determine when to stop

And additionaly you telling your searchingLock the reason to release it automaticaly.

Odomontois