Receiver thread function called on Client.start().
498054
def run(self):  # Thread for receiving data from pilight
        """"""
        logging.debug('Pilight receiver thread started')
        if not self.callback:
            raise RuntimeError('No callback function set, cancel readout thread')

        def handle_messages(messages):
            """Call callback on each receive message."""
            for message in messages:  # Loop over received  messages
                if message:  # Can be empty due to splitlines
                    message_dict = json.loads(message.decode())
                    if self.recv_codes_only:
                        # Filter: Only use receiver messages
                        if 'receiver' in message_dict['origin']:
                            if self.veto_repeats:
                                if message_dict.get('repeats', 1) == 1:
                                    self.callback(message_dict)
                            else:
                                self.callback(message_dict)
                    else:
                        self.callback(message_dict)

        while not self._stop_thread.isSet():
            try:  # Read socket in a non blocking call and interpret data
                # Sometimes more than one JSON object is in the stream thus
                # split at \n
                with self._lock:
                    messages = self.receive_socket.recv(1024).splitlines()
                handle_messages(messages)
            except (socket.timeout, ValueError):  # No data
                pass
        logging.debug('Pilight receiver thread stopped')
846488
def _on_open(self, _):
        """"""
        nick = self._format_nick(self._nick, self._pwd)
        data = {"cmd": "join", "channel": self._channel, "nick": nick}
        self._send_packet(data)
        self._thread = True
        threading.Thread(target=self._ping).start()
976503
protected void callStart(final HttpCallback<?> callback, final Request request) {
        if (callback == null)
            return;
        callback.dispatchStart(request);
    }
957724
@Override
  public void start() throws Exception {
    SynchronousQueue<Runnable> synchronousQueue = new SynchronousQueue<>();
    mThreadPool =
        new ThreadPoolExecutor(mMinNumberOfThreads, mMaxNumberOfThreads,
            THREAD_KEEP_ALIVE_TIME_MS, TimeUnit.MILLISECONDS, synchronousQueue);
    mStopped = false;
    try {
      mServerSocket = new ServerSocket(mPort);
    } catch (IOException e) {
      throw new RuntimeException("Failed to bind to port {}.", e);
    }
    while (!mStopped) {
      Socket client;
      try {
        client = mServerSocket.accept();
      } catch (IOException e) {
        if (mServerSocket.isClosed()) {
          break;
        } else {
          continue;
        }
      }
      String clientAddress = client.getInetAddress().getHostAddress();
      LOG.info("Starting thread to read logs from {}", clientAddress);
      AlluxioLog4jSocketNode clientSocketNode = new AlluxioLog4jSocketNode(mBaseLogsDir, client);
      synchronized (mClientSockets) {
        mClientSockets.add(client);
      }
      try {
        CompletableFuture.runAsync(clientSocketNode, mThreadPool)
            .whenComplete((r, e) -> {
              synchronized (mClientSockets) {
                mClientSockets.remove(client);
              }
            });
      } catch (RejectedExecutionException e) {
        // Alluxio log clients (master, secondary master, proxy and workers) establish
        // long-living connections with the log server. Therefore, if the log server cannot
        // find a thread to service a log client, it is very likely due to low number of
        // worker threads. If retry fails, then it makes sense just to let system throw
        // an exception. The system admin should increase the thread pool size.
        String errorMessage = String.format(
            "Log server cannot find a worker thread to service log requests from %s. Increase"
                + " the number of worker threads in the thread pool by configuring"
                + " alluxio.logserver.threads.max in alluxio-site.properties. Current value"
                + " is %d.", clientAddress, mMaxNumberOfThreads);
        throw new RuntimeException(errorMessage, e);
      }
    }
  }
55193
def run(self):
        """"""
        ret = eventlet.spawn(self.context(self.func))
        eventlet.sleep(self.seconds)
        try:
            ret.wait()
        except Exception:  # pylint: disable=broad-except
            traceback.print_exc()
        self.thread = eventlet.spawn(self.run)
419764
public void start() throws Exception
    {
        if (isStarted())
            throw new IllegalStateException("Started");

        // Create a new server socket and set to non blocking mode
        _acceptChannel= ServerSocketChannel.open();
        _acceptChannel.configureBlocking(false);

        // Bind the server socket to the local host and port
        _acceptChannel.socket().bind(_address);

        // Read the address back from the server socket to fix issues
        // with listeners on anonymous ports
        _address= (InetSocketAddress)_acceptChannel.socket().getLocalSocketAddress();

        // create a selector;
        _selector= Selector.open();

        // Register accepts on the server socket with the selector.
        _acceptChannel.register(_selector, SelectionKey.OP_ACCEPT);

        // Start selector thread
        _selectorThread= new SelectorThread();
        _selectorThread.start();

        // Start the thread Pool
        super.start();
        log.info("Started SocketChannelListener on " + getHost()+":"+getPort());
    }
198156
def start(self):
        """"""
        if self.closed:
            raise ConnectionClosed()

        self.read_watcher.start()
        if self.write == self.buffered_write:
            self.write_watcher.start()
630236
public void run() {
    /**
     * Ensure we start fresh.
     */
    closeServerSocket();
    closeAllAcceptedSockets();

    // start the server socket
    try {
      serverSocket = new ServerSocket(port);
    } catch (Exception e) {
      getLogger().error(
        "error starting SocketReceiver (" + this.getName()
        + "), receiver did not start", e);
      active = false;

      return;
    }

    Socket socket = null;

    try {
      getLogger().debug("in run-about to enter while not interrupted loop");

      active = true;

      while (!rThread.isInterrupted()) {
        // if we have a socket, start watching it
        if (socket != null) {
          getLogger().debug(
                  "socket not null - creating and starting socketnode");
          socketList.add(socket);

          SocketNode13 node = new SocketNode13(socket, this);
          synchronized (listenerList) {
            for (Iterator iter = listenerList.iterator();
                 iter.hasNext();) {
                SocketNodeEventListener l =
                        (SocketNodeEventListener) iter.next();
                node.addSocketNodeEventListener(l);
            }
          }
          socketMap.put(socket, node);
          new Thread(node).start();
          socket = null;
        }

        getLogger().debug("waiting to accept socket");

        // wait for a socket to open, then loop to start it
        socket = serverSocket.accept();
        getLogger().debug("accepted socket");
      }
    } catch (Exception e) {
      getLogger().warn(
        "exception while watching socket server in SocketReceiver ("
        + this.getName() + "), stopping");
    }

    getLogger().debug("{} has exited the not interrupted loop", getName());

    // socket not watched because we a no longer running
    // so close it now.
    if (socket != null) {
      try {
        socket.close();
      } catch (IOException e1) {
        getLogger().warn("socket exception caught - socket closed");
      }
    }

    getLogger().debug("{} is exiting main run loop", getName());
  }
188607
protected void startQueue() {
      if (executor == null) {
          logger.debug("Starting the receiving thread pool.");
          executor = new ThreadPoolExecutor(
                  numberOfWorkerThreads,
                  numberOfWorkerThreads,
                  threadKeepAliveTime, TimeUnit.SECONDS,
                  new LinkedBlockingQueue<Runnable>(),
                  getThreadFactory());
          executor.allowCoreThreadTimeOut(true);
          //Start with one thread, and build it up gradually as it needs.
          executor.prestartCoreThread();
          logger.info("ReceiveQueue started! Current pool size: {}", executor.getPoolSize());
      } else {
          if (executor.getCorePoolSize() < numberOfWorkerThreads) {
              //If the number has increased we need to set the max first, or we'll get an IllegalArgumentException
              executor.setMaximumPoolSize(numberOfWorkerThreads);
              executor.setCorePoolSize(numberOfWorkerThreads);
          } else if (executor.getCorePoolSize() > numberOfWorkerThreads) {
              //If the number has decreased we need to set the core first.
              executor.setCorePoolSize(numberOfWorkerThreads);
              executor.setMaximumPoolSize(numberOfWorkerThreads);
          }
          logger.info("ReceiveQueue running. Current pool size: {}. Current Queue size: {}",
                  executor.getPoolSize(), getQueueSize());
          logger.info("Nr of active pool-threads: {}", executor.getActiveCount());
      }
    }
430161
def _receiverThread(session):
    """"""

    timeOfLastSend = time.time()
    timeOfLastRecv = time.time()
    try:
        while True:
            if timeOfLastSend + KEEPALIVE_INTERVAL_SECONDS < time.time():
                if timeOfLastRecv + 10 < time.time():
                    raise exceptions.PingTimeout()
                session.socket.send(
                    b'd1:q18:Admin_asyncEnabled4:txid8:keepalive')
                timeOfLastSend = time.time()

            try:
                data = session.socket.recv(BUFFER_SIZE)
            except socket.timeout:
                continue

            try:
                benc = bdecode(data)
            except (KeyError, ValueError):
                logger.error("error decoding [%s]", data)
                continue

            if benc['txid'] == 'keepaliv':
                if benc['asyncEnabled'] == 0:
                    raise exceptions.SessionLost()
                timeOfLastRecv = time.time()
            else:
                session.queue.put(benc)

    except KeyboardInterrupt:
        logger.exception("interrupted")
        import thread
        thread.interrupt_main()
409666
void onReadingThreadStarted()
    {
        boolean bothStarted = false;

        synchronized (mThreadsLock)
        {
            mReadingThreadStarted = true;

            if (mWritingThreadStarted)
            {
                // Both the reading thread and the writing thread have started.
                bothStarted = true;
            }
        }

        // Call onConnected() method of listeners if not called yet.
        callOnConnectedIfNotYet();

        // If both the reading thread and the writing thread have started.
        if (bothStarted)
        {
            onThreadsStarted();
        }
    }
1310305
synchronized void started() {
        try {
            if(isConnected()) {
                channelHandler.executeRequest(new ServerStartedRequest(), null).getResult().await();
            }
        } catch (Exception e) {
            ServerLogger.AS_ROOT_LOGGER.debugf(e, "failed to send started notification");
        }
    }
1235712
public synchronized void start() {
        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        // Cancel any thread currently running a connection
        if (mEngConnectedThread != null) {
            mEngConnectedThread.cancel();
            mEngConnectedThread = null;
        }
        if (mImpConnectedThread != null) {
            mImpConnectedThread.cancel();
            mImpConnectedThread = null;
        }

        setState(STATE_LISTEN);
    }
409354
def receive(self):
        
        while self.running:
            if self._receiver_lock.acquire(blocking=False):
                try:
                    raw = self.conn.recv()
                except WebSocketTimeoutException:
                    self._receiver_lock.release()
                    continue
                except WebSocketConnectionClosedException:
                    # this needs to restart the client, while keeping track
                    # of the currently subscribed channels!
                    self.conn = None
                    self._controller_q.put('restart')
                except AttributeError:
                    # self.conn is None, idle loop until shutdown of thread
                    self._receiver_lock.release()
                    continue
                msg = time.time(), json.loads(raw)
                log.debug("receiver Thread: Data Received: %s", msg)
                self.receiver_q.put(msg)
                self._receiver_lock.release()
            else:
                # The receiver_lock was locked, idling until available
                time.sleep(0.5)
687155
public void     start()
    {
        Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");

        client.addParentWatcher(watcher);
    }
799910
private void onSocketStarted(SocketStartEvent event) {
        handler.post(() -> listener.onSocketStarted(event));
        log("Event published " + event.toString());
    }
309135
def start(self):
        
        if not (self.__recv_thread or self.__send_thread):
            self.__end.clear()
            self.__send_ready.clear()
            self.__recv_ready.clear()
            timeout = self.__socket_timeout + 1
            ignore_exc = self.__startup_ignore_exc
            self.__send_exc_clear()
            self.__recv_exc_clear()

            # start & await send thread success (unless timeout reached or an exception has occured)
            self.__send_thread = Thread(target=self.__send_run, name='amqplink_send')
            self.__send_thread.start()
            start_time = monotonic()
            success = False
            while not (success or (not ignore_exc and self.__send_exc) or monotonic() - start_time > timeout):
                success = self.__send_ready.wait(.25)

            if success:
                # start & await receiver thread success
                self.__recv_thread = Thread(target=self.__recv_run, name='amqplink_recv')
                self.__recv_thread.start()
                start_time = monotonic()
                success = False
                while not (success or (not ignore_exc and self.__recv_exc) or monotonic() - start_time >= timeout):
                    success = self.__recv_ready.wait(.25)

            # handler either thread's failure
            if not success:
                logger.warning("AmqpLink Failed to start.  Giving up.")
                self.stop()
                if self.__recv_exc:
                    # prioritise receive thread since this can get access-denied whereas send does not (until sending)
                    raise_from(LinkException('Receive thread failure'), self.__recv_exc)
                elif self.__send_exc:
                    raise_from(LinkException('Send thread failure'), self.__send_exc)
                else:
                    raise LinkException('Unknown link failure (timeout reached)')

        else:
            raise LinkException('amqplink already started')