Subj : Re: How to manage time-slicing in Pthreads programs? To : comp.programming.threads From : D'artagnan Date : Sat Feb 19 2005 09:40 pm David Schwartz wrote: > "D'artagnan" wrote in message > news:1108864881.967818.199940@g14g2000cwa.googlegroups.com... > > > OK, maybe I didn't explain the situation clearly in my first post. In > > my example, I don't want thread A to put itself to sleep, I want thread > > B to put it to sleep and wake it up later. > > That doesn't make sense. I guess this means thread B doesn't have a direct way to put thread A to sleep. > > > Consider the following > > senario: thread A and thread B are processing a huge collection of > > items, one-by-one. The workload is split up between the two threads > > such that 99% chance there aren't conflicting accesses between the two > > threads. For the 1% chance of conflicting accesses we need some > > protection. The problem is that thread A never knows which items will > > cause conflicting accesses, only thread B has this knowledge. > > Why not just lock the conflicting objects with a non-blocking lock? If a > thread can't get the lock on an object, it just goes on to the next one. > Because the distribution of those special objects (those inducing conflicts) is random and nonderministic in the input data. It's hard to know before run time which objects should be locked. Locking (even non-blocking) each item generates too much unwanted overhead. > > Therefore, pthread_cond_wait() doesn't apply here because (1) thead A > > doesn't know when to wait; and (2) if thread B calls it and goes to > > sleep, there is nobody to wake it up. > > No thread ever needs to go to sleep. Just have each thread take the > first untaken item. > Without locking up an object, you cannot be sure if it has been accessed by the other thread or not. > > The desired scheme would be: When thread B becomes aware of a potential > > conflicting access, it puts thread A into sleep. Thread B finishes the > > access, then wakes thread A up. Are there any ways to do this? Thanks. > > There are ways to do this, but they all involve thread B telling thread > A to go to sleep, How? Are these ways involving signals? I kind of remember signals in Linux threads are somewhat goofy. Am I wrong? Basically, what I'm headed for here is that I want user-level atomic operations. Locks in Pthreads synchronize accesses to shared locations, but multiple threads can still execute the same operation at the same time. An atomic operation is one that once started by a thread it runs to its completion without being swapped out and back. > and thread A receiving the request and then putting itself > to sleep. Smarter to lock the data in most cases. > > DS .