Discovers the mongo cluster and creates a thread for each primary.
962692
def run(self):
        
        # Reset the global minimum MongoDB version
        update_mininum_mongodb_version(None)
        self.main_conn = self.create_authed_client()
        LOG.always(
            "Source MongoDB version: %s",
            self.main_conn.admin.command("buildInfo")["version"],
        )

        for dm in self.doc_managers:
            name = dm.__class__.__module__
            module = sys.modules[name]
            version = "unknown"
            if hasattr(module, "__version__"):
                version = module.__version__
            elif hasattr(module, "version"):
                version = module.version
            LOG.always("Target DocManager: %s version: %s", name, version)

        self.read_oplog_progress()
        conn_type = None

        try:
            self.main_conn.admin.command("isdbgrid")
        except pymongo.errors.OperationFailure:
            conn_type = "REPLSET"

        if conn_type == "REPLSET":
            # Make sure we are connected to a replica set
            is_master = self.main_conn.admin.command("isMaster")
            if "setName" not in is_master:
                LOG.error(
                    'No replica set at "%s"! A replica set is required '
                    "to run mongo-connector. Shutting down..." % self.address
                )
                return

            # Establish a connection to the replica set as a whole
            self.main_conn.close()
            self.main_conn = self.create_authed_client(replicaSet=is_master["setName"])

            self.update_version_from_client(self.main_conn)

            # non sharded configuration
            oplog = OplogThread(
                self.main_conn,
                self.doc_managers,
                self.oplog_progress,
                self.namespace_config,
                **self.kwargs
            )
            self.shard_set[0] = oplog
            LOG.info("MongoConnector: Starting connection thread %s" % self.main_conn)
            oplog.start()

            while self.can_run:
                shard_thread = self.shard_set[0]
                if not (shard_thread.running and shard_thread.is_alive()):
                    LOG.error(
                        "MongoConnector: OplogThread"
                        " %s unexpectedly stopped! Shutting down"
                        % (str(self.shard_set[0]))
                    )
                    self.oplog_thread_join()
                    for dm in self.doc_managers:
                        dm.stop()
                    return

                self.write_oplog_progress()
                time.sleep(1)

        else:  # sharded cluster
            while self.can_run:
                # The backup role does not provide the listShards privilege,
                # so use the config.shards collection instead.
                for shard_doc in retry_until_ok(
                    lambda: list(self.main_conn.config.shards.find())
                ):
                    shard_id = shard_doc["_id"]
                    if shard_id in self.shard_set:
                        shard_thread = self.shard_set[shard_id]
                        if not (shard_thread.running and shard_thread.is_alive()):
                            LOG.error(
                                "MongoConnector: OplogThread "
                                "%s unexpectedly stopped! Shutting "
                                "down" % (str(self.shard_set[shard_id]))
                            )
                            self.oplog_thread_join()
                            for dm in self.doc_managers:
                                dm.stop()
                            return

                        self.write_oplog_progress()
                        time.sleep(1)
                        continue
                    try:
                        repl_set, hosts = shard_doc["host"].split("/")
                    except ValueError:
                        cause = "The system only uses replica sets!"
                        LOG.exception("MongoConnector: %s", cause)
                        self.oplog_thread_join()
                        for dm in self.doc_managers:
                            dm.stop()
                        return

                    shard_conn = self.create_authed_client(hosts, replicaSet=repl_set)
                    self.update_version_from_client(shard_conn)
                    oplog = OplogThread(
                        shard_conn,
                        self.doc_managers,
                        self.oplog_progress,
                        self.namespace_config,
                        mongos_client=self.main_conn,
                        **self.kwargs
                    )
                    self.shard_set[shard_id] = oplog
                    msg = "Starting connection thread"
                    LOG.info("MongoConnector: %s %s" % (msg, shard_conn))
                    oplog.start()

        if self.signal is not None:
            LOG.info("recieved signal %s: shutting down...", self.signal)
        self.oplog_thread_join()
        self.write_oplog_progress()
293979
public void startup() {
        if (isRunning) return;

        Executors.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                DispatcherHandler handler = new DispatcherHandler(AndServer.getContext());
                ComponentRegister register = new ComponentRegister(AndServer.getContext());
                register.register(handler, mGroup);

                mHttpServer = ServerBootstrap.bootstrap()
                    .setSocketConfig(SocketConfig.custom()
                        .setSoKeepAlive(true)
                        .setSoReuseAddress(true)
                        .setSoTimeout(mTimeout)
                        .setTcpNoDelay(true)
                        .build())
                    .setConnectionConfig(
                        ConnectionConfig.custom().setBufferSize(4 * 1024).setCharset(Charsets.UTF_8).build())
                    .setLocalAddress(mInetAddress)
                    .setListenerPort(mPort)
                    .setSslContext(mSSLContext)
                    .setSslSetupHandler(new SSLInitializerWrapper(mSSLInitializer))
                    .setServerInfo("AndServer/2.0.0")
                    .registerHandler("*", handler)
                    .setExceptionLogger(ExceptionLogger.NO_OP)
                    .create();
                try {
                    isRunning = true;
                    mHttpServer.start();

                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onStarted();
                        }
                    });
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        @Override
                        public void run() {
                            mHttpServer.shutdown(3, TimeUnit.SECONDS);
                        }
                    });
                } catch (final Exception e) {
                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onException(e);
                        }
                    });
                }
            }
        });
    }
441753
function findOrCreateInstance(callback) {
    var models = self._meshApp.models;
    var Instance = models.ServiceInstance;

    service.instances(function(err, instances) {
      if (err) return callback(err);
      if (instances.length > 0) return callback();

      debug('onServiceUpdate: create first instance');

      var instance = new Instance({
        executorId: 1,
        serverServiceId: service.id,
        groupId: 1,
        cpus: 'STRONGLOOP_CLUSTER' in process.env ?
          process.env.STRONGLOOP_CLUSTER : 'CPU',

        // allow starting tracing on all instances via env for testing purposes
        tracingEnabled: !!process.env.STRONGLOOP_TRACING || false,
      });
      instance.save(callback);
    });
  }
715410
private void createThreads(int threadCount)
    {
        
        for(int i=0; i<threadCount; i++) {
            
            AsyncActionWorkerThread worker = new AsyncActionWorkerThread("Async-Action-Worker-"+i);
            this.threadPool.add(worker);
            worker.start();
            
        }
        
    }
820854
public void start() {
		synchronized (this.monitor) {
			saveInitialSnapshots();
			if (this.watchThread == null) {
				Map<File, FolderSnapshot> localFolders = new HashMap<>();
				localFolders.putAll(this.folders);
				this.watchThread = new Thread(new Watcher(this.remainingScans,
						new ArrayList<>(this.listeners), this.triggerFilter,
						this.pollInterval, this.quietPeriod, localFolders));
				this.watchThread.setName("File Watcher");
				this.watchThread.setDaemon(this.daemon);
				this.watchThread.start();
			}
		}
	}
1185787
@Override
  public void run() {
    long lastUpdate = -1L;
    // Start balancing the clusters
    while (running) {
      try {
        Thread.sleep(updateInterval / 10);
        long now = JobTracker.getClock().getTime();
        if (now - lastUpdate > updateInterval) {
          lastUpdate = now;
          doMoveSlots(clusters);
        }
      } catch (Exception e) {
        LOG.error("Exception while balancing cluster.", e);
      }
    }
  }
996218
def thread(self):
        """"""
        if not self._thread_calculated:
            self._thread_calculated = True

            split_tokens = self.split_tokens

            if not self.datetime_nextpos:
                return None
            if len(split_tokens) <= self.datetime_nextpos:
                return None

            connection_token = split_tokens[self.datetime_nextpos]
            match = re.match(r'^\[([^\]]*)\]$', connection_token)
            if match:
                self._thread = match.group(1)

            if self._thread is not None:
                if self._thread in ['initandlisten', 'mongosMain']:
                    if len(split_tokens) >= 5 and split_tokens[-5][0] == '#':
                        self._conn = 'conn' + split_tokens[-5][1:]
                elif self._thread.startswith('conn'):
                    self._conn = self._thread
        return self._thread
1151378
public synchronized void startCollecting() {
		paused = false;
		if (thread != null)
			return;

		packages = new CountMap<String>(MAX_PACKAGES);
		selfMethods = new CountMap<String>(MAX_METHODS);
		stackMethods = new CountMap<String>(MAX_METHODS);
		lines = new CountMap<String>(MAX_LINES);
		total = 0;

		started = true;
		thread = new Thread(this);
		thread.setName("Profiler");
		thread.setDaemon(true);
		thread.start();
	}
677191
def thread(self):
        
        log.info('@{}.thread starting'.format(self.__class__.__name__))
        thread = threading.Thread(target=thread_wrapper(self.consume), args=())
        thread.daemon = True
        thread.start()
507798
public synchronized void start() throws IOException {
        if (listenerThreads.size() == 0) {
            List<InetAddress> addresses = hostAddress == null ? NetworkUtil.getMulticastAddresses() : Arrays.asList(hostAddress);
            if (addresses.size() == 0) {
                logHandler.info("No suitable address found for listening on multicast discovery requests");
                return;
            }
            // We start a thread for every address found
            for (InetAddress addr : addresses) {
                try {
                    MulticastSocketListenerThread thread = new MulticastSocketListenerThread("JolokiaDiscoveryListenerThread-" + addr.getHostAddress(),
                                                                                            addr,
                                                                                             detailsHolder,
                                                                                             restrictor,
                                                                                             logHandler);
                    thread.start();
                    listenerThreads.add(thread);
                } catch (IOException exp) {
                    logHandler.info("Couldn't start discovery thread for " + addr + ": " + exp);
                }
            }
        }
    }
803465
def _start(self):
        

        # Initialize the locks
        self._recv_lock = coros.Semaphore(0)
        self._send_lock = coros.Semaphore(0)

        # Boot the threads
        self._recv_thread = gevent.spawn(self._recv)
        self._send_thread = gevent.spawn(self._send)

        # Link the threads such that we get notified if one or the
        # other exits
        self._recv_thread.link(self._thread_error)
        self._send_thread.link(self._thread_error)
1127945
def create(parallel):
    
    queue = {k: v for k, v in parallel.items() if k in ["queue", "cores_per_job", "mem"]}
    yield queue
699472
def codingthreads(self):
        
        printtime('Extracting CDS features', self.start)
        # Create and start threads
        for i in range(self.cpus):
            # Send the threads to the appropriate destination function
            threads = Thread(target=self.codingsequences, args=())
            # Set the daemon to true - something to do with thread management
            threads.setDaemon(True)
            # Start the threading
            threads.start()
        for sample in self.runmetadata.samples:
            self.codingqueue.put(sample)
        self.codingqueue.join()
        # Create CDS files and determine gene presence/absence
        self.corethreads()
1001769
@Override
  public synchronized void start() {
    LOGGER.info("Starting the Gobblin Cluster Manager");

    this.eventBus.register(this);
    this.multiManager.connect();

    configureHelixQuotaBasedTaskScheduling();

    if (this.isStandaloneMode) {
      // standalone mode starts non-daemon threads later, so need to have this thread to keep process up
      this.idleProcessThread = new Thread(new Runnable() {
        @Override
        public void run() {
          while (!GobblinClusterManager.this.stopStatus.isStopInProgress() && !GobblinClusterManager.this.stopIdleProcessThread) {
            try {
              Thread.sleep(300);
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
              break;
            }
          }
        }
      });

      this.idleProcessThread.start();

      // Need this in case a kill is issued to the process so that the idle thread does not keep the process up
      // since GobblinClusterManager.stop() is not called this case.
      Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
          GobblinClusterManager.this.stopIdleProcessThread = true;
        }
      });
    } else {
      startAppLauncherAndServices();
    }
  }
1116342
private static void createThreadPool() {
        if (nprocs == -1) {
            int n = -1;
            try {
                String env = System.getProperty("smile.threads");
                if (env != null) {
                    n = Integer.parseInt(env);
                }
            } catch (Exception ex) {
                logger.error("Failed to create multi-core execution thread pool", ex);
            }

            if (n < 1) {
                nprocs = Runtime.getRuntime().availableProcessors();
            } else {
                nprocs = n;
            }

            if (nprocs > 1) {
                threads = (ThreadPoolExecutor) Executors.newFixedThreadPool(nprocs, new SimpleDeamonThreadFactory());
            }
        }
    }
336021
def start(self):
    

    if self.__running:
      raise RuntimeError('ThreadPool already running')
    [t.start() for t in self.__threads]
    self.__running = True
42426
@PostConstruct
    public void start() {
        threadFactory = Executors.defaultThreadFactory();
        disruptor = new Disruptor<>(Registration.FACTORY,
                ringSize,
                threadFactory,
                ProducerType.MULTI,
                new BlockingWaitStrategy());
        disruptor.handleEventsWith(new ContainerEventHandler());
        ringBuffer = disruptor.start();
    }