How to implement a Lock with a timeout in Python 2.7

to elaborate on Steven’s comment suggestion: import threading import time lock = threading.Lock() cond = threading.Condition(threading.Lock()) def waitLock(timeout): with cond: current_time = start_time = time.time() while current_time < start_time + timeout: if lock.acquire(False): return True else: cond.wait(timeout – current_time + start_time) current_time = time.time() return False Things to notice: there are two threading.Lock() objects, one … Read more

Why do I need to synchronize a list returned by Collections.synchronizedList

The list being synchronized only means that add, remove etc. operations are synchronized and therefore atomic. Iteration however is not and if a thread adds while another is iterating, you could get a ConcurrentModificationException. By manually synchronizing your iteration block, you ensure that the list is not modified while iterating. One alternative is to use … Read more

increment a count value outside parallel.foreach scope

I like to beat dead horses! 🙂 The “lightest” way to increment the count from multiple threads is: Interlocked.Increment(ref count); But as others have pointed out: if you’re doing it inside Parallel.ForEach then you’re probably doing something wrong. I’m suspecting that for some reason you’re using ForEach but you need an index to the item … Read more

Is synchronization within an HttpSession feasible?

I found this nice explanation in spring-mvc JavaDoc for WebUtils.getSessionMutex(): In many cases, the HttpSession reference itself is a safe mutex as well, since it will always be the same object reference for the same active logical session. However, this is not guaranteed across different servlet containers; the only 100% safe way is a session … Read more

Do lock-free algorithms really perform better than their lock-full counterparts?

Beyond the simple cases of the InterlockedXxx functions, it seems like the prevailing pattern with all of these is that they implement their own locks. None of the answers here really seem to get to the heart of the difference between a “lock-free” CAS loop and a mutex or spin-lock. The important difference is that … Read more

Dependent loads reordering in CPU

Short answer: In an out-of-order processor the load-store queue is used to track and enforce memory ordering constraints. Processors such as the Alpha 21264 have the necessary hardware to prevent dependent load reordering, but enforcing this dependency could add overhead for inter-processor communication. Long answer: Background on dependence tracking This is probably best explained using … Read more