views:

25

answers:

0

I have a pool of connections. The exact nature of them isn't particular important in this case - think of them like primitives that can be passed around freely. In a multi-threaded environment, I want to create a resource manager on which I can call "acquire()" to gain exclusive access to a connection in a thread, and subsequently "release()" to give it back to the pool. It's been a long time since I've done something like this and I want to make sure my pseudo-code below is the right strategy and that there are no subtle bugs.

I'm using Python for the project but, to my knowledge, there's nothing particularly Python specific in this code, hence the pseudo-code. If there's a Python library that can do all this for me, let me know, thanks!

function acquire(wait_time=30):
    resource = null
    while (wait_time > 0):
        start_time = now()
        if (!acquire_lock(wait_time)):
            return null
        if (resource_pool.is_empty()):
             wait_time -= (now() - start_time) 
        else:
             resource = resource_pool.pop()
        release_lock()

    return resource


function release(resource):
    acquire_lock()  #infinite wait time?
    resource_pool.push(resource)
    release_lock()
  1. I know that I could do a slightly better job of making sure that "release()" only actually works with resources of the proper type, and only works with resources that were first acquired. This is just some quick pseudo-code.
  2. Do I need the lock in "release()"? Should I wait infinitely?