<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <thrift/lib/cpp/concurrency/ThreadManager.h>

#include <thrift/lib/cpp/concurrency/Exception.h>
#include <thrift/lib/cpp/concurrency/Monitor.h>
#include <thrift/lib/cpp/concurrency/Thread.h>
#include <thrift/lib/cpp/concurrency/PosixThreadFactory.h>
#include <thrift/lib/cpp/concurrency/Codel.h>
#include <folly/Conv.h>
#include "ThreadManager.h"
#include "PosixThreadFactory.h"
#include <folly/MPMCQueue.h>
#include <thrift/lib/cpp/async/Request.h>
#include <folly/Logging.h>

#include <memory>

#include <assert.h>
#include <queue>
#include <set>
#include <atomic>

#if defined(DEBUG)
#include <iostream>
#endif //defined(DEBUG)

#include <thrift/lib/cpp/concurrency/ThreadManager-impl.h>

namespace apache { namespace thrift { namespace concurrency {

using std::shared_ptr;
using std::make_shared;
using std::dynamic_pointer_cast;
using std::unique_ptr;
using apache::thrift::async::RequestContext;

/**
 * ThreadManager class
 *
 * This class manages a pool of threads. It uses a ThreadFactory to create
 * threads.  It never actually creates or destroys worker threads, rather
 * it maintains statistics on number of idle threads, number of active threads,
 * task backlog, and average wait and service times.
 *
 * @version $Id:$
 */

template <typename SemType>
template <typename SemTypeT>
class ThreadManager::ImplT<SemType>::Worker : public Runnable {
 public:
  Worker(ThreadManager::ImplT<SemTypeT>* manager) :
    manager_(manager) {}

  ~Worker() {}

  /**
   * Worker entry point
   *
   * As long as worker thread is running, pull tasks off the task queue and
   * execute.
   */
  void run() {
    // Inform our manager that we are starting
    manager_->workerStarted(this);

    while (true) {
      // Wait for a task to run
      Task* task = manager_->waitOnTask();

      // A nullptr task means that this thread is supposed to exit
      if (!task) {
        manager_->workerExiting(this);
        return;
      }

      // Getting the current time is moderately expensive,
      // so only get the time if we actually need it.
      SystemClockTimePoint startTime;
      if (task->canExpire() || task->statsEnabled()) {
        startTime = SystemClock::now();

        // Codel auto-expire time algorithm
        int64_t delay = std::chrono::duration_cast<std::chrono::milliseconds>(
          startTime - task->getQueueBeginTime()).count();

        if (manager_->codel_.overloaded(std::chrono::microseconds(delay))) {
          if (manager_->codelCallback_) {
            manager_->codelCallback_(task->getRunnable());
          }
          if (manager_->codelEnabled_) {
            FB_LOG_EVERY_MS(WARNING, 10000) << "Queueing delay timeout";

            manager_->taskExpired(task);
            delete task;
            continue;
          }
        }
      }

      // Check if the task is expired
      if (task->canExpire() &&
          task->getExpireTime() <= startTime) {
        manager_->taskExpired(task);
        delete task;
        continue;
      }

      try {
        task->run();
      } catch(const std::exception& ex) {
        T_ERROR("ThreadManager: worker task threw unhandled "
                "%s exception: %s", typeid(ex).name(), ex.what());
      } catch(...) {
        T_ERROR("ThreadManager: worker task threw unhandled "
                "non-exception object");
      }

      if (task->statsEnabled()) {
        auto endTime = SystemClock::now();
        manager_->reportTaskStats(task->getQueueBeginTime(),
                                  startTime,
                                  endTime);
      }
      delete task;
    }
  }

 private:
  ThreadManager::ImplT<SemType>* manager_;
};

template <typename SemType>
void ThreadManager::ImplT<SemType>::addWorker(size_t value) {
  std::vector<shared_ptr<Thread> > newThreads;
  newThreads.reserve(value);
  for (size_t ix = 0; ix < value; ix++) {
    auto worker = make_shared<Worker<SemType>>(this);
    newThreads.push_back(threadFactory_->newThread(worker,
                                                   ThreadFactory::ATTACHED));
  }

  {
    Guard g(mutex_);

    if (state_ != STARTED) {
      throw IllegalStateException("ThreadManager::addWorker(): "
                                  "ThreadManager not running");
    }

    workerCount_ += value;
    intendedWorkerCount_ += value;
    idleCount_ += value;
  }

  // Start all of the threads.
  for (std::vector<shared_ptr<Thread> >::iterator ix = newThreads.begin();
       ix != newThreads.end();
       ix++) {
    (*ix)->start();
  }
}

template <typename SemType>
void ThreadManager::ImplT<SemType>::workerStarted(Worker<SemType>* worker) {
  InitCallback initCallback;
  {
    Guard g(mutex_);
    assert(idleCount_ > 0);
    --idleCount_;
    ++totalTaskCount_;
    shared_ptr<Thread> thread = worker->thread();
    idMap_.insert(std::make_pair(thread->getId(), thread));
    initCallback = initCallback_;
    if (!namePrefix_.empty()) {
      thread->setName(folly::to<std::string>(namePrefix_,<commit_msg>Handle the case when starting a thread fails<commit_after>/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <thrift/lib/cpp/concurrency/ThreadManager.h>

#include <thrift/lib/cpp/concurrency/Exception.h>
#include <thrift/lib/cpp/concurrency/Monitor.h>
#include <thrift/lib/cpp/concurrency/Thread.h>
#include <thrift/lib/cpp/concurrency/PosixThreadFactory.h>
#include <thrift/lib/cpp/concurrency/Codel.h>
#include <folly/Conv.h>
#include "ThreadManager.h"
#include "PosixThreadFactory.h"
#include <folly/MPMCQueue.h>
#include <thrift/lib/cpp/async/Request.h>
#include <folly/Logging.h>

#include <memory>

#include <assert.h>
#include <queue>
#include <set>
#include <atomic>

#if defined(DEBUG)
#include <iostream>
#endif //defined(DEBUG)

#include <thrift/lib/cpp/concurrency/ThreadManager-impl.h>

namespace apache { namespace thrift { namespace concurrency {

using std::shared_ptr;
using std::make_shared;
using std::dynamic_pointer_cast;
using std::unique_ptr;
using apache::thrift::async::RequestContext;

/**
 * ThreadManager class
 *
 * This class manages a pool of threads. It uses a ThreadFactory to create
 * threads.  It never actually creates or destroys worker threads, rather
 * it maintains statistics on number of idle threads, number of active threads,
 * task backlog, and average wait and service times.
 *
 * @version $Id:$
 */

template <typename SemType>
template <typename SemTypeT>
class ThreadManager::ImplT<SemType>::Worker : public Runnable {
 public:
  Worker(ThreadManager::ImplT<SemTypeT>* manager) :
    manager_(manager) {}

  ~Worker() {}

  /**
   * Worker entry point
   *
   * As long as worker thread is running, pull tasks off the task queue and
   * execute.
   */
  void run() {
    // Inform our manager that we are starting
    manager_->workerStarted(this);

    while (true) {
      // Wait for a task to run
      Task* task = manager_->waitOnTask();

      // A nullptr task means that this thread is supposed to exit
      if (!task) {
        manager_->workerExiting(this);
        return;
      }

      // Getting the current time is moderately expensive,
      // so only get the time if we actually need it.
      SystemClockTimePoint startTime;
      if (task->canExpire() || task->statsEnabled()) {
        startTime = SystemClock::now();

        // Codel auto-expire time algorithm
        int64_t delay = std::chrono::duration_cast<std::chrono::milliseconds>(
          startTime - task->getQueueBeginTime()).count();

        if (manager_->codel_.overloaded(std::chrono::microseconds(delay))) {
          if (manager_->codelCallback_) {
            manager_->codelCallback_(task->getRunnable());
          }
          if (manager_->codelEnabled_) {
            FB_LOG_EVERY_MS(WARNING, 10000) << "Queueing delay timeout";

            manager_->taskExpired(task);
            delete task;
            continue;
          }
        }
      }

      // Check if the task is expired
      if (task->canExpire() &&
          task->getExpireTime() <= startTime) {
        manager_->taskExpired(task);
        delete task;
        continue;
      }

      try {
        task->run();
      } catch(const std::exception& ex) {
        T_ERROR("ThreadManager: worker task threw unhandled "
                "%s exception: %s", typeid(ex).name(), ex.what());
      } catch(...) {
        T_ERROR("ThreadManager: worker task threw unhandled "
                "non-exception object");
      }

      if (task->statsEnabled()) {
        auto endTime = SystemClock::now();
        manager_->reportTaskStats(task->getQueueBeginTime(),
                                  startTime,
                                  endTime);
      }
      delete task;
    }
  }

 private:
  ThreadManager::ImplT<SemType>* manager_;
};

template <typename SemType>
void ThreadManager::ImplT<SemType>::addWorker(size_t value) {
  for (size_t ix = 0; ix < value; ix++) {
    auto worker = make_shared<Worker<SemType>>(this);
    auto thread = threadFactory_->newThread(worker,
                                            ThreadFactory::ATTACHED);
    thread->start();

    Guard g(mutex_);

    if (state_ != STARTED) {
      throw IllegalStateException("ThreadManager::addWorker(): "
                                  "ThreadManager not running");
    }

    workerCount_++;
    intendedWorkerCount_++;
    idleCount_++;
  }
}

template <typename SemType>
void ThreadManager::ImplT<SemType>::workerStarted(Worker<SemType>* worker) {
  InitCallback initCallback;
  {
    Guard g(mutex_);
    assert(idleCount_ > 0);
    --idleCount_;
    ++totalTaskCount_;
    shared_ptr<Thread> thread = worker->thread();
    idMap_.insert(std::make_pair(thread->getId(), thread));
    initCallback = initCallback_;
    if (!namePrefix_.empty()) {
      thread->setName(folly::to<std::string>(namePrefix_,
{'fraction_non_alphanumeric': 0.11947100348494326, 'fraction_numerical': 0.0026807255830578144, 'mean_word_length': 2.9256401262714835, 'pattern_counts': {'":': 0, '<': 79, '<?xml version=': 0, '>': 121, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 11, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4617227', 'n_tokens_mistral': 3254, 'n_tokens_neox': 3178, 'n_words': 881}