限制call()内的并发方法执行

时间:2016-02-25 08:37:45

标签: multithreading callable

我的代码中有一个call()方法,它基于某些条件调用特定的方法:

typename MyList<ElementData>::Node* nodes;

在上面的场景中,我想限制methodC的并发执行。 如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

这里需要的是Semaphore构造(请查看示例中的保镖/夜总会规范)。

// Create the semaphore with 3 slots, where 3 are available.
var bouncer = new Semaphore(3, 3);

call(){
  if(a){
      methodA(); 
  }
  if(b){
      methodB(); 
  }
  if(c){
      // Let a thread execute only after acquiring access (a semaphore to be released).
      Bouncer.WaitOne(); 
      methodC(); 
      // This thread is done. Let someone else go for it 
      Bouncer.Release(1); 
  }
}

答案 1 :(得分:0)

如果要将并发执行的数量限制为最多一次,则应使用Lock。在Java中它应该看起来像:

final Lock lock = new ReentrantLock();
call() {
  if(a) {
      methodA(); 
  }
  if(b) {
      methodB(); 
  }
  if(c) {
      lock.lock();
      try {
         methodC(); 
      } finally {
         lock.unlock();
      }
  }
}

如果要一次将并发执行次数限制为多个,可以使用Semaphore;这里CONCURRENT_CALLS_ALLOWED是一个i​​nt。

final Semaphore semaphore = new Semaphore(CONCURRENT_CALLS_ALLOWED);
call() {
  if(a) {
      methodA(); 
  }
  if(b) {
      methodB(); 
  }
  if(c) {
      semaphore.aquire();//throws checked exception
      try {
         methodC(); 
      } finally {
         semaphore.release();
      }
  }
}