start the pool's workers
350220
def start(self):
        ""
        for i in xrange(self.size):
            scheduler.schedule(self._runner)
        self._closing = False
639425
protected function startWorkers(): void
    {
        $wrapper = realpath(__DIR__ . '/../../../bin/phpunit-sqlite-wrapper');

        for ($i = 1; $i <= $this->options->processes; ++$i) {
            $worker = new SqliteWorker($this->dbFileName);
            if ($this->options->noTestTokens) {
                $token = null;
                $uniqueToken = null;
            } else {
                $token = $i;
                $uniqueToken = uniqid();
            }
            $worker->start($wrapper, $token, $uniqueToken);
            $this->workers[] = $worker;
        }
    }
1001375
function (i) {
                    workers[i] = cluster.fork();

                    console.log('Creating Worker: ', workers[i].process.pid);
                    workers[i].on('message', m => {
                        switch (m.type) {
                            case 'STARTED':
                                !startedWorkers && startWatches();
                                break;
                        }
                    });
                    // Optional: Restart worker on exit
                    workers[i].on('exit', function (code, signal) {
                        console.log('Respawning worker', i);
                        spawn(i);
                    });
                }
243374
def _start_new_worker_process(self, server_socket):
        """"""
        from multiprocessing import Process
        p = Process(target=forked_child, args=self._get_child_args(server_socket))
        p.start()
        return p
609962
def init_workers():
    """"""
    setproctitle('oq-worker')
    # unregister raiseMasterKilled in oq-workers to avoid deadlock
    # since processes are terminated via pool.terminate()
    signal.signal(signal.SIGTERM, signal.SIG_DFL)
    # prctl is still useful (on Linux) to terminate all spawned processes
    # when master is killed via SIGKILL
    try:
        import prctl
    except ImportError:
        pass
    else:
        # if the parent dies, the children die
        prctl.set_pdeathsig(signal.SIGKILL)
1228465
public function work()
    {
        $this->log('Starting worker <pop>'.$this.'</pop>', Logger::INFO);
        $this->updateProcLine('Worker: starting...');

        $this->startup();

        $this->log('Listening to queues: <pop>'.implode(', ', $this->queues).'</pop>, with '.
            ($this->blocking ? 'timeout blocking' : 'time interval').' <pop>'.$this->interval_string().'</pop>', Logger::INFO);

        while (true) {
            if ($this->memoryExceeded()) {
                $this->log('Worker memory has been exceeded, aborting', Logger::CRITICAL);
                $this->shutdown();

                Event::fire(Event::WORKER_LOW_MEMORY, $this);
            }

            if (!$this->redis->sismember(self::redisKey(), $this->id) or $this->redis->hlen(self::redisKey($this)) == 0) {
                $this->log('Worker is not in list of workers or packet is corrupt, aborting', Logger::CRITICAL);
                $this->shutdown();

                Event::fire(Event::WORKER_CORRUPT, $this);
            }

            $this->shutdown = $this->redis->hget(self::redisKey($this), 'shutdown');

            if ($this->shutdown) {
                $this->log('Shutting down worker <pop>'.$this.'</pop>', Logger::INFO);
                $this->updateProcLine('Worker: shutting down...');
                break;
            }

            if ($this->status == self::STATUS_PAUSED) {
                $this->log('Worker paused, trying again in '.$this->interval_string(), Logger::INFO);
                $this->updateProcLine('Worker: paused');
                sleep($this->interval);
                continue;
            }

            $this->host->working($this);
            $this->redis->hmset(self::redisKey($this), 'memory', memory_get_usage());

            Event::fire(Event::WORKER_WORK, $this);

            if (!count($this->resolveQueues())) {
                $this->log('No queues found, waiting for '.$this->interval_string(), Logger::INFO);
                sleep($this->interval);
                continue;
            }

            $this->queueDelayed();

            if ($this->blocking) {
                $this->log('Pop blocking with timeout of '.$this->interval_string(), Logger::DEBUG);
                $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with blocking timeout '.$this->interval_string());
            } else {
                $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with interval '.$this->interval_string());
            }

            $job = \Resque::pop($this->resolveQueues(), $this->interval, $this->blocking);

            if (!$job instanceof Job) {
                if (!$this->blocking) {
                    $this->log('Sleeping for '.$this->interval_string(), Logger::DEBUG);
                    sleep($this->interval);
                }

                continue;
            }

            $this->log('Found a job <pop>'.$job.'</pop>', Logger::NOTICE);

            $this->workingOn($job);

            Event::fire(Event::WORKER_FORK, array($this, $job));

            // Fork into another process
            $this->child = pcntl_fork();

            // Returning -1 means error in forking
            if ($this->child == -1) {
                Event::fire(Event::WORKER_FORK_ERROR, array($this, $job));

                $this->log('Unable to fork process, this is a fatal error, aborting worker', Logger::ALERT);
                $this->log('Re-queuing job <pop>'.$job.'</pop>', Logger::INFO);

                // Because it wasn't the job that failed the job is readded to the queue
                // so that in can be tried again at a later time
                $job->queue();

                $this->shutdown();
            } elseif ($this->child > 0) {
                // In parent if $pid > 0 since pcntl_fork returns process id of child
                Event::fire(Event::WORKER_FORK_PARENT, array($this, $job, $this->child));

                $this->log('Forked process to run job on pid:'.$this->child, Logger::DEBUG);
                $this->updateProcLine('Worker: forked '.$this->child.' at '.strftime('%F %T'));

                // Set the PID in redis
                $this->redis->hset(self::redisKey($this), 'job_pid', $this->child);

                // Wait until the child process finishes before continuing
                pcntl_wait($status);

                if (!pcntl_wifexited($status) or ($exitStatus = pcntl_wexitstatus($status)) !== 0) {
                    if ($this->job->getStatus() == Job::STATUS_FAILED) {
                        $this->log('Job '.$job.' failed: "'.$job->failError().'" in '.$this->job->execTimeStr(), Logger::ERROR);
                    } else {
                        $this->log('Job '.$job.' exited with code '.$exitStatus, Logger::ERROR);
                        $this->job->fail(new Exception\Dirty($exitStatus));
                    }
                }
            } else {
                // Reset the redis connection to prevent forking issues
                $this->redis->disconnect();
                $this->redis->connect();

                Event::fire(Event::WORKER_FORK_CHILD, array($this, $job, getmypid()));

                $this->log('Running job <pop>'.$job.'</pop>', Logger::INFO);
                $this->updateProcLine('Job: processing '.$job->getQueue().'#'.$job->getId().' since '.strftime('%F %T'));

                $this->perform($job);
                exit(0);
            }

            $this->child = null;
            $this->doneWorking();
        }
    }
684530
def start(self):
        
        # give a nice name to the process
        w.setproctitle('oq-dbserver')

        dworkers = []
        for _ in range(self.num_workers):
            sock = z.Socket(self.backend, z.zmq.REP, 'connect')
            threading.Thread(target=self.dworker, args=(sock,)).start()
            dworkers.append(sock)
        logging.warning('DB server started with %s on %s, pid %d',
                        sys.executable, self.frontend, self.pid)
        if ZMQ:
            # start task_in->task_out streamer thread
            c = config.zworkers
            threading.Thread(
                target=w._streamer,
                args=(self.master_host, c.task_in_port, c.task_out_port)
            ).start()
            logging.warning('Task streamer started from %s -> %s',
                            c.task_in_port, c.task_out_port)

            # start zworkers and wait a bit for them
            msg = self.master.start()
            logging.warning(msg)
            time.sleep(1)

        # start frontend->backend proxy for the database workers
        try:
            z.zmq.proxy(z.bind(self.frontend, z.zmq.ROUTER),
                        z.bind(self.backend, z.zmq.DEALER))
        except (KeyboardInterrupt, z.zmq.ZMQError):
            for sock in dworkers:
                sock.running = False
                sock.zsocket.close()
            logging.warning('DB server stopped')
        finally:
            self.stop()
576325
private function pull(): Worker
    {
        if (!$this->isRunning()) {
            throw new StatusError("The pool was shutdown");
        }

        do {
            if ($this->idleWorkers->isEmpty()) {
                if ($this->getWorkerCount() >= $this->maxSize) {
                    // All possible workers busy, so shift from head (will be pushed back onto tail below).
                    $worker = $this->busyQueue->shift();
                } else {
                    // Max worker count has not been reached, so create another worker.
                    $worker = $this->factory->create();
                    $this->workers->attach($worker, 0);
                    break;
                }
            } else {
                // Shift a worker off the idle queue.
                $worker = $this->idleWorkers->shift();
            }

            if ($worker->isRunning()) {
                break;
            }

            $this->workers->detach($worker);
        } while (true);

        $this->busyQueue->push($worker);
        $this->workers[$worker] += 1;

        return $worker;
    }
753041
def initialize_worker(self):
        """"""
        worker_thread = threading.Thread(
            name="WorkerThread", target=message_worker, args=(self,))
        worker_thread.setDaemon(True)
        worker_thread.start()
928368
public void start() {
		this.workerThread = new Thread(this);
		System.out.println("starting worker thread");
		this.workerThread.start();
		System.out.println("worker thread started");
	}
228725
def start(self, segment):
        """"""

        if self.closed:
            raise UserCritical(msg='attempt to transfer wal after closing',
                               hint='report a bug')

        g = gevent.Greenlet(self.transferer, segment)
        g.link(self._complete_execution)
        self.greenlets.add(g)

        # Increment .expect before starting the greenlet, or else a
        # very unlucky .join could be fooled as to when pool is
        # complete.
        self.expect += 1

        g.start()
936536
def run(self):
        """"""
        executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self._run_loop(executor))
        self._log.info('Shutting down...')
        executor.shutdown()
1206764
def _start_worker(self, worker: Worker):
        
        # This function is called from main thread and from worker pools threads to start their children threads
        with self.running_workers_lock:
            self.running_workers.append(worker)
        thread = SchedulerThread(worker, self._worker_ended)
        thread.start()
        # This may or may not be posted to a background thread (see set_callbacks)
        self.worker_start_callback(worker)
1229218
def run(self):
        """"""
        # Create the thread pool.
        executor = concurrent.futures.ThreadPoolExecutor(
            max_workers=self._config['num_workers'])

        # Wait to ensure multiple senders can be synchronised.
        now = int(datetime.datetime.utcnow().timestamp())
        start_time = ((now + 29) // 30) * 30
        self._log.info('Waiting until {}'.format(
                       datetime.datetime.fromtimestamp(start_time)))
        while int(datetime.datetime.utcnow().timestamp()) < start_time:
            time.sleep(0.1)

        # Run the event loop.
        loop = asyncio.get_event_loop()
        try:
            loop.run_until_complete(self._run_loop(executor))
        except KeyboardInterrupt:
            pass
        finally:
            # Send the end of stream message to each stream.
            self._log.info('Shutting down, closing streams...')
            tasks = []
            for stream, item_group in self._streams:
                tasks.append(stream.async_send_heap(item_group.get_end()))
            loop.run_until_complete(asyncio.gather(*tasks))
            self._log.info('... finished.')
            executor.shutdown()
336634
protected function adjustRunningWorkers() : void
    {
        foreach ($this->poolsConfig as $pool => $workerConfig) {
            $workersActive = count($this->pids[$pool]);
            $workersTarget = (int)$workerConfig['instances'];
            if ($workersActive >= $workersTarget) {
                continue;
            }

            $workerDiff = $workersTarget - $workersActive;
            for ($i = 0; $i < $workerDiff; $i++) {
                $this->startupWorker($pool);
            }
        }
    }
111218
def _start_workers(self):
        
        # creating the pool of worker process or threads
        log.debug('%s starts a %s-pool of %s workers.' % \
                  (self, self.worker_type, self.worker_num))
        self.pool = []
        for host, worker_num in \
                           [(None, self.worker_num)] + list(self.worker_remote):
            for _worker in range(worker_num):
                __worker = Thread(target=_pool_worker, args=\
                                  (self._inqueue, self._outqueue, host)) \
                                  if self.worker_type == 'thread' else \
                           Process(target=_pool_worker, args=\
                                  (self._inqueue, self._outqueue, host))
                self.pool.append(__worker)
        for __worker in self.pool:
            __worker.daemon = True
            __worker.start()
        log.debug('%s started the pool' % self)
629143
private void initPool() {
        if (logger.isWarnEnabled()) {
            logger.warn("Start to initialize connection pool with url: " + url + " ...");
        }

        for (int i = 0; (i < initialSize) && (xpool.size() < initialSize); i++) {
            pool.lock();

            try {
                if (pool.isClosed()) {
                    break;
                }

                if ((i < initialSize) && (xpool.size() < initialSize)) {
                    PoolableConnection poolableConn = newConnection();

                    if (!pool.add(poolableConn)) {
                        detroyConnection(poolableConn);
                    }
                }
            } finally {
                pool.unlock();
            }
        }

        if (logger.isWarnEnabled()) {
            logger.warn("End to initialize connection pool with url: " + url + " ...");
        }
    }