Busy-wait on long-lived subtasks/greenlets, re-raise if any error occurs
495125
def _run(self, *args, **kwargs):  # pylint: disable=method-hidden
        
        self.greenlet.name = f'RaidenService._run node:{pex(self.address)}'
        try:
            self.stop_event.wait()
        except gevent.GreenletExit:  # killed without exception
            self.stop_event.set()
            gevent.killall([self.alarm, self.transport])  # kill children
            raise  # re-raise to keep killed status
        except Exception:
            self.stop()
            raise
1344255
public void waitForAsyncFlush() {
    long numAdded = asyncBatchesAdded.get();

    synchronized (this) {
      while (numAdded > asyncBatchesProcessed) {
        try {
          wait();
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
189130
def wait_and_join(self, task):
        
        while not task.has_started:
            time.sleep(self._polling_time)
        task.thread.join()
1154271
private void waitForCompletion() {
        for (ListenableFuture<?> future : pendingTasks.values()) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                LOG.error("[" + this + "] Error waiting for writes to complete: " + e.getMessage());
            }
        }
    }
65558
public static void waitOneFinished(List<? extends Task<?,?>> tasks) {
		if (tasks.isEmpty()) return;
		if (tasks.size() == 1)
			try { tasks.get(0).getOutput().block(0); }
			catch (Throwable e) { /* ignore */ }
		SynchronizationPoint<Exception> sp = new SynchronizationPoint<>();
		for (Task<?,?> t : tasks) {
			if (t.isDone()) return;
			t.getOutput().synchWithNoError(sp);
		}
		sp.block(0);
	}
604142
def wait_for_subworkflows(self, workflow_results):
        ''''''
        wf_ids = sum([x['pending_workflows'] for x in workflow_results], [])
        for wf_id in wf_ids:
            # here we did not check if workflow ids match
            yield self.socket
            res = self.socket.recv_pyobj()
            if res is None:
                sys.exit(0)
            elif isinstance(res, Exception):
                raise res
222950
def delay_or_fail(self, *args, **kwargs):
        
        return self.async_or_fail(args=args, kwargs=kwargs)
989643
def wait_for_success(self, interval=1):
        

        self.wait_for_completion(interval=interval)

        if not self.is_successful(retry=True):
            for task_name, task in six.iteritems(self.get_task_statuses()):
                exc = None
                if task.status == Instance.Task.TaskStatus.FAILED:
                    exc = errors.parse_instance_error(self.get_task_result(task_name))
                elif task.status != Instance.Task.TaskStatus.SUCCESS:
                    exc = errors.ODPSError('%s, status=%s' % (task_name, task.status.value))
                if exc:
                    exc.instance_id = self.id
                    raise exc
144535
def wait_for_ipykernel(self, service_name, timeout=10):
        """"""
        kernel_line = self._services[service_name].logs.tail.until(
            lambda line: "--existing" in line[1], timeout=10, lines_back=5
        )
        return kernel_line.replace("--existing", "").strip()
563981
def waitStarted(self):
        """"""
        ns = None
        while not ns:
            try:
                time.sleep(3)
                ns = Pyro.naming.NameServerLocator(
                    identification=self.identification).getNS()
            except Pyro.errors.NamingError as er:
                pass
1099301
def await_flush_completion(self, timeout=None):
        
        try:
            for batch in self._incomplete.all():
                log.debug('Waiting on produce to %s',
                          batch.produce_future.topic_partition)
                if not batch.produce_future.wait(timeout=timeout):
                    raise Errors.KafkaTimeoutError('Timeout waiting for future')
                if not batch.produce_future.is_done:
                    raise Errors.UnknownError('Future not done')

                if batch.produce_future.failed():
                    log.warning(batch.produce_future.exception)
        finally:
            self._flushes_in_progress.decrement()
109647
def _wait(self, args, now, cap, consumed_history, consumed_capacity):
        
        for key in ['read', 'write']:
            if key in cap and cap[key] > 0:
                consumed_history[key].add(now, consumed_capacity[key])
                consumed = consumed_history[key].value
                if consumed > 0 and consumed >= cap[key]:
                    seconds = math.ceil(float(consumed) / cap[key])
                    LOG.debug("Rate limited throughput exceeded. Sleeping "
                              "for %d seconds.", seconds)
                    if callable(self.callback):
                        callback_args = args + (seconds,)
                        if self.callback(*callback_args):
                            continue
                    time.sleep(seconds)
1075085
def _wait_for_handles(handles, timeout=-1):
    
    arrtype = HANDLE * len(handles)
    handle_array = arrtype(*handles)

    ret = windll.kernel32.WaitForMultipleObjects(
        len(handle_array), handle_array, BOOL(False), DWORD(timeout))

    if ret == WAIT_TIMEOUT:
        return None
    else:
        h = handle_array[ret]
        return h
1086893
public void waitUntilFinished()
    {
        flushTermination();
        flushUpdate();
        flushInsert();
        shutdown();
        for (int i = 0; i < numberOfUpdateThreads; i++)
        {
            while(!executor[i].isTerminated())
            {
                try
                {
                    executor[i].awaitTermination(10000000, TimeUnit.SECONDS);
                }
                catch (InterruptedException e)
                {
                    // ignore
                }
            }
        }
        flushInsert();
        insertExecutor.shutdown();
        while(!insertExecutor.isTerminated())
        {
            try
            {
                insertExecutor.awaitTermination(10000000, TimeUnit.SECONDS);
            }
            catch (InterruptedException e)
            {
                // ignore
            }
        }
        logFinalResults();
        if (this.error != null)
        {
            if (error instanceof RuntimeException)
            {
                throw (RuntimeException) error;
            }
            else
            {
                throw new RuntimeException("One or more parallel tasks failed", this.error);
            }
        }
    }
840546
def schedule(self, name, timer, func, *args, **kwargs):
        '''
        
        '''
        self.tasks.append(Task(name, func, timer, *args, **kwargs))
        self.active[name] = []  # list of greenlets
        self.waiting[name] = []
247844
def wait_for_package_sync(
    ctx, opts, owner, repo, slug, wait_interval, skip_errors, attempts=3
):
    """"""
    # pylint: disable=too-many-locals
    attempts -= 1
    click.echo()
    label = "Synchronising %(package)s:" % {"package": click.style(slug, fg="green")}

    status_str = "Waiting"
    stage_str = None

    def display_status(current):
        """Display current sync status."""
        # pylint: disable=unused-argument
        if not stage_str:
            return status_str
        return click.style(
            "%(status)s / %(stage)s" % {"status": status_str, "stage": stage_str},
            fg="cyan",
        )

    context_msg = "Failed to synchronise file!"
    with handle_api_exceptions(
        ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
    ):
        last_progress = 0
        with click.progressbar(
            length=100,
            label=label,
            fill_char=click.style("#", fg="green"),
            empty_char=click.style("-", fg="red"),
            item_show_func=display_status,
        ) as pb:
            while True:
                res = get_package_status(owner, repo, slug)
                ok, failed, progress, status_str, stage_str, reason = res
                delta = progress - last_progress
                if delta > 0:
                    last_progress = progress
                    pb.update(delta)
                if ok or failed:
                    break
                time.sleep(wait_interval)

    if ok:
        click.secho("Package synchronised successfully!", fg="green")
        return

    click.secho(
        "Package failed to synchronise during stage: %(stage)s"
        % {"stage": click.style(stage_str or "Unknown", fg="yellow")},
        fg="red",
    )

    if reason:
        click.secho(
            "Reason given: %(reason)s" % {"reason": click.style(reason, fg="yellow")},
            fg="red",
        )

        # pylint: disable=fixme
        # FIXME: The API should communicate "no retry" fails
        if "package should be deleted" in reason and attempts > 1:
            click.secho(
                "This is not recoverable, so stopping further attempts!", fg="red"
            )
            click.echo()
            attempts = 0

    if attempts + 1 > 0:
        # Show attempts upto and including zero attempts left
        click.secho(
            "Attempts left: %(left)s (%(action)s)"
            % {
                "left": click.style(six.text_type(attempts), bold=True),
                "action": "trying again" if attempts > 0 else "giving up",
            }
        )
        click.echo()

    if attempts > 0:
        from .resync import resync_package

        resync_package(
            ctx=ctx,
            opts=opts,
            owner=owner,
            repo=repo,
            slug=slug,
            skip_errors=skip_errors,
        )

        wait_for_package_sync(
            ctx=ctx,
            opts=opts,
            owner=owner,
            repo=repo,
            slug=slug,
            wait_interval=wait_interval,
            skip_errors=skip_errors,
            attempts=attempts,
        )
    else:
        ctx.exit(1)
1135710
public static <TError extends Exception> void waitUnblockedWithError(Collection<AsyncWork<?,TError>> tasks) throws TError, CancelException {
		for (AsyncWork<?,TError> t : tasks)
			t.blockResult(0);
	}