Multiple Competing Methods

The following is an example of the use of threads in a computational framework. It is also an example that could be easily extended to work on a distributed computer network. The idea is relatively simple, but applies more to a multi-processor setup. We have several competing methods for estimating a particular vector from a given set of inputs, x and y. Suppose we have k different methods and k different functions that estimate the relevant quantity - method1, method2 ... methodk. We are unsure as to which method will determine a solution the fastest. So we evaluate each method and stop when one finishes. We are not interested in timing the methods here, just getting the answer as soon as possible. The following code does this (and no more).

First, we create the threads and start them evaluating the different methods.

  grp = threadGroup("methods")                    # create a thread group to hold all the threads
  num.threads =  threadLock("num.threads")        # 
  for(i in 1:k) {
     # These have to be evaluated within the thread for method i.
     # Otherwise, that thread could finish before
    threadLock(num.threads)
      num.threads = threadLock.get("num.threads")
      threadLock.assign(num.threads,"num.threads", num.threads + 1, lock = F)
    yieldLock(num.threads)
    thread(parse(textConnection(paste("fit",i," <- method",i,"(x,y)",sep=""))),grp)
  }

   yield()  # let the other threads start

Now all the threads are started and are converging on the answer (hopefully). When one finishes, we want to stop all the threads.
  # we know that num.threads was == k  at one point
  # or that one or more threads has already finished
  # wait for num.threads to decrease from the total number of threads started.
  getLock(num.threads, condition = Quote(num.threads < k))

   yieldLock(num.threads) # give up the lock so that the other threads can be cancelled

   # cancel each thread that still exists.
   # the manager will determine if this is irrelevant for a specific thread
  cancel(grp)

   # now we just handle the return values
   # How do we get them back
   


Last modified: Wed Feb 5 08:03:27 1997