Put a hold on processing and return a function that will release it.
438672
function internalStop(test) {
  	test.semaphore += 1;
  	config.blocking = true;

  	// Set a recovery timeout, if so configured.
  	if (defined.setTimeout) {
  		var timeoutDuration = void 0;

  		if (typeof test.timeout === "number") {
  			timeoutDuration = test.timeout;
  		} else if (typeof config.testTimeout === "number") {
  			timeoutDuration = config.testTimeout;
  		}

  		if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  			clearTimeout(config.timeout);
  			config.timeout = setTimeout(function () {
  				pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
  				internalRecover(test);
  			}, timeoutDuration);
  		}
  	}

  	var released = false;
  	return function resume() {
  		if (released) {
  			return;
  		}

  		released = true;
  		test.semaphore -= 1;
  		internalStart(test);
  	};
  }
1198768
function handle (fn) {
	return function (...args) {
		return new Promise((resolve) => {
			fn.bind(this)(...args, function (err, result) {
				/* istanbul ignore if */
				if (err) {
					debug(err);
				} else {
					resolve(result);
				}
			});
		});
	};
}
374223
def _leave_handler(self, event):
        """"""
        iid = self.current_iid
        if iid is None or self.active == iid:
            return
        self.update_state(iid, "normal")
1256436
def release(self, conn):
        """"""
        if conn.in_transaction:
            raise InvalidRequestError(
                "Cannot release a connection with "
                "not finished transaction"
            )
        raw = conn.connection
        res = yield from self._pool.release(raw)
        return res
1111525
function(closeCallback, forcequit, keepglobal) {
  if (!keepglobal && this === __theApp)
    __theApp = null;
  if (closeCallback)
    this.addBeforeStopListener(closeCallback);

  this.gracefullyExiting = true;
  var server = this.get("server");
  var p = this._beforeStop();
  if (server) {
    p = p.then(function() {
      return new Promise(function(resolve, reject) {
        server.close(function(err) {
          if (err) reject(err);
          else resolve();
        });
      });
    });
  }
  if (forcequit) {
    var timeout = typeof forcequit == "number" ? forcequit : STOP_APP_TIMEOUT;
    setTimeout( function () {
      console.error("Could not close connections in time, forcefully shutting down");
      process.exit(1);
    }, timeout);
  }
  return p;
}
1047375
def _ProcessLockAcquired(self):
        """"""
        try:
            is_locked = self._process_lock.acquire(timeout=self._lock_timeout)
            yield is_locked
        finally:
            if is_locked:
                self._process_lock.release()
245582
def release(self) -> None:
        """"""
        self._value += 1
        while self._waiters:
            waiter = self._waiters.popleft()
            if not waiter.done():
                self._value -= 1

                # If the waiter is a coroutine paused at
                #
                #     with (yield semaphore.acquire()):
                #
                # then the context manager's __exit__ calls release() at the end
                # of the "with" block.
                waiter.set_result(_ReleasingContextManager(self))
                break
603654
def guard(func):
    
    semaphore = threading.Lock()

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        semaphore.acquire()
        try:
            return func(*args, **kwargs)
        finally:
            semaphore.release()

    return wrapper
566997
def cancel_on_closing(func):
    
    @wraps(func)
    async def wrapper(self, *args, **kwargs):
        return await self.await_until_closing(func(self, *args, **kwargs))

    return wrapper
1239779
function promiseWrapper (resolve, reject) {
            // Wait for the process to exit
            process.on ("exit", (code) => {
                // Did the process crash?
                if (code !== 0) reject (process.stderr.textContent);

                // Resolve
                resolve (process.stdout.textContent);
            });

            // Pipe the script into stdin and end
            process.stdin.write (script);
            process.stdin.end ();
        }
935356
function async(func)
{
  function wrapper()
  {
    var context = this;
    var args    = arguments;
    process.nextTick(function()
    {
      func.apply(context, args);
    });
  }

  return wrapper;
}
1103201
function finalizeHandler(p, hInfo) {
    if (!p) return;

    return p
      .catch(storeErrOnce)
      .then(function () {
        if (errored && !hInfo.ensure) return null;
        _hook(self, 'eachAfter', hInfo, params);
      })
      .catch(storeErrOnce);
  }
1250685
private function release()
    {
        \assert($this->busy !== null);

        $deferred = $this->busy;
        $this->busy = null;
        $deferred->resolve();
    }
48996
def _handle(self, event_handler, event_name, user_args, event_timeout,
                cond, cond_timeout):
        
        if cond:
            cond.wait(cond_timeout)
        event = self.pop_event(event_name, event_timeout)
        return event_handler(event, *user_args)
731084
function processBranch (args, resolve, reject) {
  let condition = args.shift()
  let val = args.shift()
  let las = _.last(args)

  return Promise.resolve(condition)
    .then(c => {
      if (c === true) {
        return Promise.resolve(_.isFunction(val) ? val() : val)
          .then(resolve, reject)
      } else if (args.length === 1) {
        return Promise.resolve(_.isFunction(las) ? las() : las)
          .then(resolve, reject)
      } else {
        return processBranch(args, resolve, reject)
      }
    }, reject)
}
1337391
def ReleaseProcessedFlow(self, flow_obj):
    """"""
    key = (flow_obj.client_id, flow_obj.flow_id)
    next_id_to_process = flow_obj.next_request_to_process
    request_dict = self.flow_requests.get(key, {})
    if (next_id_to_process in request_dict and
        request_dict[next_id_to_process].needs_processing):
      return False

    self.UpdateFlow(
        flow_obj.client_id,
        flow_obj.flow_id,
        flow_obj=flow_obj,
        processing_on=None,
        processing_since=None,
        processing_deadline=None)
    return True
165194
def ReleaseProcessedFlow(self, flow_obj, cursor=None):
    """"""

    update_query = """
    UPDATE flows
    LEFT OUTER JOIN (
      SELECT client_id, flow_id, needs_processing
      FROM flow_requests
      WHERE
        client_id = %(client_id)s AND
        flow_id = %(flow_id)s AND
        request_id = %(next_request_to_process)s AND
        needs_processing
    ) AS needs_processing
    ON
      flows.client_id = needs_processing.client_id AND
      flows.flow_id = needs_processing.flow_id
    SET
      flows.flow = %(flow)s,
      flows.processing_on = NULL,
      flows.processing_since = NULL,
      flows.processing_deadline = NULL,
      flows.next_request_to_process = %(next_request_to_process)s,
      flows.flow_state = %(flow_state)s,
      flows.user_cpu_time_used_micros = %(user_cpu_time_used_micros)s,
      flows.system_cpu_time_used_micros = %(system_cpu_time_used_micros)s,
      flows.network_bytes_sent = %(network_bytes_sent)s,
      flows.num_replies_sent = %(num_replies_sent)s,
      flows.last_update = NOW(6)
    WHERE
      flows.client_id = %(client_id)s AND
      flows.flow_id = %(flow_id)s AND (
        needs_processing.needs_processing = FALSE OR
        needs_processing.needs_processing IS NULL)
    """

    clone = flow_obj.Copy()
    clone.processing_on = None
    clone.processing_since = None
    clone.processing_deadline = None
    args = {
        "client_id":
            db_utils.ClientIDToInt(flow_obj.client_id),
        "flow":
            clone.SerializeToString(),
        "flow_id":
            db_utils.FlowIDToInt(flow_obj.flow_id),
        "flow_state":
            int(clone.flow_state),
        "network_bytes_sent":
            flow_obj.network_bytes_sent,
        "next_request_to_process":
            flow_obj.next_request_to_process,
        "num_replies_sent":
            flow_obj.num_replies_sent,
        "system_cpu_time_used_micros":
            db_utils.SecondsToMicros(flow_obj.cpu_time_used.system_cpu_time),
        "user_cpu_time_used_micros":
            db_utils.SecondsToMicros(flow_obj.cpu_time_used.user_cpu_time),
    }
    rows_updated = cursor.execute(update_query, args)
    return rows_updated == 1