Esempio n. 1
0
 inline void stopThreads() const
 {
     lst_sem()->wait();
     for (RobotInterface::ThreadList::iterator tit = thr()->begin(); tit != thr()->end(); tit++) {
         yarp::os::Thread *thread = *tit;
         thread->stop();
     }
     lst_sem()->post();
 }
Esempio n. 2
0
File: db.cpp Progetto: gilles/mongo
    void listen(int port) {
        //testTheDb();
        log() << "waiting for connections on port " << port << endl;
        OurListener l(cmdLine.bind_ip, port);
        l.setAsTimeTracker();
        startReplication();
        if ( !noHttpInterface )
            boost::thread thr(webServerThread);

#if(TESTEXHAUST)
        boost::thread thr(testExhaust);
#endif
        l.initAndListen();
    }
std::future<typename std::result_of<Function(Arg)>::type>
SimpleAsync(Function func, Arg arg)
{
    typedef std::result_of<Function(Arg)>::type return_val;
    // prom.cpp:10:13: error: missing 'typename' prior to dependent type name 'std::result_of<Function (Arg)>::type'
    //   (Arg)>::type'
    // typedef std::result_of<Function(Arg)>::type return_val;
    //         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //         typename

    // http://www.cplusplus.com/reference/type_traits/result_of/
 
    std::promise<return_val> prom;
    std::future<return_val> fut = prom.get_future();
 
    std::thread thr([](std::promise<return_val>& prom, Function func, Arg arg)
    {
        try
        {
            prom.set_value(func(arg));
        }
        catch (const std::exception& e)
        {
            prom.set_exception(std::current_exception());
        }
    }, std::move(prom), func, arg);
 
    thr.detach();
 
    return std::move(fut);
}
Esempio n. 4
0
  static void test()
  {
    try
    {
      attributes attrs;
      attrs.thread_num_ = 2;
      context ctx(attrs);

      threaded_actor ping = spawn(ctx);
      threaded_actor pong = spawn(ctx);
      aid_t pong_id = pong.get_aid();
      boost::thread thr(
        boost::bind(
          &mixin_pingpong_ut::pong_actor, pong
          )
        );

      boost::timer::auto_cpu_timer t;
      message m(1);
      for (std::size_t i=0; i<msg_size; ++i)
      {
        ping.send(pong_id, m);
        ping.recv(m);
      }
      ping->send(pong_id, 2);
      thr.join();
    }
    catch (std::exception& ex)
    {
      std::cerr << ex.what() << std::endl;
    }
  }
Esempio n. 5
0
int
main (int argc, char **argv)
{
  error_t err;
  int i;
  pthread_t tid[THREADS];

  for (i = 0; i < THREADS; i ++)
    {
      err = pthread_create (&tid[i], 0, thr, 0);
      if (err)
	error (1, err, "pthread_create (%d)", i);
    }

  assert (thr (0) == 0);

  for (i = 0; i < THREADS; i ++)
    {
      void *ret;

      err = pthread_join (tid[i], &ret);
      if (err)
	error (1, err, "pthread_join");

      assert (ret == 0);
    }

  assert (var == 1);

  return 0;
}
Esempio n. 6
0
int
main(int argc, char** argv)
{
    ThreadFunctor tf;
    std::thread thr(doit);
    std::thread thr2(doit2, 10);
    std::thread thr3(tf);

    thr.join();
    thr2.join();
    thr3.join();

    std::vector<std::thread> threads;
    threads.push_back(std::thread(doit2, 1));
    threads.push_back(std::thread(doit2, 2));
    threads.push_back(std::thread(doit2, 3));

    for (auto &thr:threads) {
        thr.join();
    }

    printf("Nubmer of hardware thread contexts: %u\n", 
        std::thread::hardware_concurrency());
    return 0;
}
Esempio n. 7
0
int main(int argc, char**argv)
{
	scene = new Scene();
	int renderingMode = 5;

	RES_X = scene->getWidth();
	RES_Y = scene->getHeight();


	std::cout << "Please choose your scene from (enter the number):" << std::endl;
	std::cout << "1 - Balls_low" << std::endl;
	std::cout << "2 - Balls_high" << std::endl;
	std::cout << "3 - Mount_Low" << std::endl;
	std::cout << "4 - Mount_high" << std::endl;
	std::cout << "5 - Solo dragon" << std::endl;
	std::cout << "6 - Custom scene" << std::endl;

	std::string s;
	getline(std::cin, s);
	sceneNum = atoi(s.c_str());

	std::cout << "Please choose your rendering mode from (enter the number):" << std::endl;
	std::cout << "1 - Aliasing with DOF" << std::endl;
	std::cout << "2 - Monte Carlo with DOF" << std::endl;
	std::cout << "3 - Aliasing only" << std::endl;
	std::cout << "4 - Monte Carlo only" << std::endl;
	std::cout << "5 - No DOF or Aliasing" << std::endl;
	std::cout << "6 - DOF only" << std::endl;

	getline(std::cin, s);
	renderingMode = atoi(s.c_str());

	std::cout << "Please choose the number of Shadow Rays:" << std::endl;

	getline(std::cin, s);
	numSF = atoi(s.c_str());

	std::cout << "Please choose the number of Depth Rays:" << std::endl;

	getline(std::cin, s);
	numDepth = atoi(s.c_str());


	std::thread thr(glutInitv, std::ref(argc), std::ref(argv));
	std::thread thr1(loadScene, std::ref(scene ), renderingMode, sceneNum);
	//threads[2] = std::thread(loadScene, std::ref(scene), 3);
	//threads[3] = std::thread(loadScene, std::ref(scene), 4);
	//threads[4] = std::thread(loadScene, std::ref(scene), 5);
	//threads[5] = std::thread(loadScene, std::ref(scene), 6);

	//aux[0] = std::thread(loadScene, std::ref(scene), 1);
	//aux[1] = std::thread(loadScene, std::ref(scene), 2);
	//aux[2] = std::thread(loadScene, std::ref(scene), 3);
	//aux[3] = std::thread(loadScene, std::ref(scene), 4);
	//aux[4] = std::thread(loadScene, std::ref(scene), 5);
	//aux[5] = std::thread(loadScene, std::ref(scene), 6);

	thr.join();
	thr1.join();
}
int main(int argc, char* argv[])
{
if (argc != 2) {
     std::cout << "usage: raytracer file.sdf\n";
     return 1;
  }

  Scene scene = load_sdf_file(argv[1]);

  std::string const filename = "./checkerboard.ppm";
  unsigned const width = scene.xresolution;
  unsigned const height = scene.yresolution;

  Renderer app(scene, 3);

  std::thread thr([&app]() { app.render(); });

  Window win(glm::ivec2(width,height));

  while (!win.shouldClose()) {
    if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {
      win.stop();
    }

    glDrawPixels( width, height, GL_RGB, GL_FLOAT
                , app.colorbuffer().data());

    win.update();
  }

  thr.join();

  return 0;
}
int main() {
  Logger::init("AISTest.log");

  auto future = canService.start();

  aisNode = new CANAISNode(msgBus, dbHandler, canService);
  aisNode->start();

  aisProc = new AISProcessing(msgBus,dbHandler, &cMgr);
  aisProc->start();

  cMgr.startGC();

  std::thread thr(messageLoop);
  thr.detach();
  int now;
  while (true) {
    std::this_thread::sleep_for(std::chrono::milliseconds(5000));
    now = SysClock::unixTime();
    Logger::info("Collidable manager size: " + std::to_string(cMgr.getAISContacts().length()));
    auto colList = cMgr.getAISContacts();
    for (int i = 0; i<cMgr.getAISContacts().length(); i++) {
        auto t = colList.next();
        Logger::info("MMSI: " + std::to_string(t.mmsi) + ", Lat: " + std::to_string(t.latitude) + ", Lon: " + std::to_string(t.longitude) +
                ", COG: " + std::to_string(t.course) + " (" + std::to_string(t.course*180/3.141592) + ")" + ", SOG: " + std::to_string(t.speed) +
                " (" + std::to_string(t.speed*1.9438) + ")" + ", Length: " + std::to_string(t.length) + ", Beam: " + std::to_string(t.beam) +
                ", Report age: " + std::to_string(now-t.lastUpdated));
    }
  }
}
Esempio n. 10
0
/** Spawn a thread to read from the pipe connected to the specified fd.
 * Returns a Future that will hold a string with the entire output from
 * that stream. */
Future<w_string> ChildProcess::readPipe(int fd) {
  auto it = pipes_.find(fd);
  if (it == pipes_.end()) {
    return makeFuture(w_string(nullptr));
  }

  auto p = std::make_shared<Promise<w_string>>();
  std::thread thr([this, fd, p] {
    std::string result;
    try {
      auto& pipe = pipes_[fd];
      while (true) {
        char buf[4096];
        auto x = read(pipe->read.fd(), buf, sizeof(buf));
        if (x == 0) {
          // all done
          break;
        }
        if (x == -1) {
          p->setException(std::make_exception_ptr(std::system_error(
              errno, std::generic_category(), "reading from child process")));
          return;
        }
        result.append(buf, x);
      }
      p->setValue(w_string(result.data(), result.size()));
    } catch (const std::exception& exc) {
      p->setException(std::current_exception());
    }
  });

  thr.detach();
  return p->getFuture();
}
Esempio n. 11
0
int main(int argc, char* argv[])
{
  std::string const filename = "./ppm_tes.ppm";
  SDFloader loader;
  std::string filepath = "../framework/res/test_scene_3.sdf";
  Scene loaded{loader.load(filepath)};
  unsigned const width = 600;
  unsigned const height = 600;
  Renderer app(width, height, filename);

  std::thread thr([&]() { app.render(loaded); });

  Window win(glm::ivec2(width,height));

  while (!win.shouldClose()) {
    if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {
      win.stop();
    }

    glDrawPixels( width, height, GL_RGB, GL_FLOAT
                , app.colorbuffer().data());

    win.update();
  }

  thr.join();


  return 0;
}
Esempio n. 12
0
File: db.cpp Progetto: zhuk/mongo
 virtual void accepted(MessagingPort *mp) {
     assert( grab == 0 );
     grab = mp;
     boost::thread thr(connThread);
     while ( grab )
         sleepmillis(1);
 }
Esempio n. 13
0
void TestEnqueue( int p ) {
    REMARK("Testing task::enqueue for %d threads\n", p);
    for(int mode=0;mode<3;++mode) {
        tbb::task_scheduler_init init(p);
        EnqueuedTask::nCompletedPairs = EnqueuedTask::nOrderedPairs = 0;
        for(int i=0; i<nTracks; ++i) {
            TaskTracks[i] = -1; // to accomodate for the starting call
            EnqueuedTask::FireTwoTasks(TaskTracks+i);
        }
        ProgressMonitor pm;
        tbb::tbb_thread thr( pm );
        if(mode==1) {
            // do some parallel work in the meantime
            for(int i=0; i<10; i++) {
                TaskGenerator& g = *new( tbb::task::allocate_root() ) TaskGenerator(2,5);
                tbb::task::spawn_root_and_wait(g);
                TimedYield( 1E-6 );
            }
        }
        if( mode==2 ) {
            // Additionally enqueue a bunch of empty tasks. The goal is to test that tasks
            // allocated and enqueued by a thread are safe to use after the thread leaves TBB.
            tbb::task* root = new (tbb::task::allocate_root()) tbb::empty_task;
            root->set_ref_count(100);
            for( int i=0; i<100; ++i )
                tbb::task::enqueue( *new (root->allocate_child()) tbb::empty_task );
            init.terminate(); // master thread deregistered
        }
        thr.join();
        ASSERT(EnqueuedTask::nCompletedPairs==nTracks*PairsPerTrack, NULL);
        ASSERT(EnqueuedTask::nOrderedPairs<EnqueuedTask::nCompletedPairs,
            "all task pairs executed in enqueue order; de facto guarantee is too strong?");
    }
}
Esempio n. 14
0
bool AsyncShaderCompiler::StartWorkerThreads(u32 num_worker_threads)
{
  if (num_worker_threads == 0)
    return true;

  for (u32 i = 0; i < num_worker_threads; i++)
  {
    void* thread_param = nullptr;
    if (!WorkerThreadInitMainThread(&thread_param))
    {
      WARN_LOG(VIDEO, "Failed to initialize shader compiler worker thread.");
      break;
    }

    m_worker_thread_start_result.store(false);

    std::thread thr(&AsyncShaderCompiler::WorkerThreadEntryPoint, this, thread_param);
    m_init_event.Wait();

    if (!m_worker_thread_start_result.load())
    {
      WARN_LOG(VIDEO, "Failed to start shader compiler worker thread.");
      thr.join();
      break;
    }

    m_worker_threads.push_back(std::move(thr));
  }

  return HasWorkerThreads();
}
Esempio n. 15
0
int main()
{
    F f;
    std::thread thr(a);
    thr.join();
    return 0;
}
Esempio n. 16
0
std::string
hstcpsvr::start_listen()
{
    std::string err;
    if (threads.size() != 0) {
        return "start_listen: already running";
    }
    if (socket_bind(cshared.listen_fd, cshared.sockargs, err) != 0) {
        return "bind: " + err;
    }
    DENA_VERBOSE(20, fprintf(stderr, "bind done\n"));
    const size_t stack_size = std::max(
                                  cshared.conf.get_int("stack_size", 1 * 1024LL * 1024), 8 * 1024LL * 1024);
    for (long i = 0; i < cshared.num_threads; ++i) {
        hstcpsvr_worker_arg arg;
        arg.cshared = &cshared;
        arg.vshared = &vshared;
        arg.worker_id = i;
        std::auto_ptr< thread<worker_throbj> > thr(
            new thread<worker_throbj>(arg, stack_size));
        threads.push_back_ptr(thr);
    }
    DENA_VERBOSE(20, fprintf(stderr, "threads created\n"));
    for (size_t i = 0; i < threads.size(); ++i) {
        threads[i]->start();
    }
    DENA_VERBOSE(20, fprintf(stderr, "threads started\n"));
    return std::string();
}
Esempio n. 17
0
	/**
	 * 後処理ルールを順番に実行
	 * @param[in] allPlayers 全てのプレイヤ
	 * @param[in] param パラメタ
	 * @param[in] step 実行ステップ
	 */
	void runRulesAfterOutput(
		const AllPlayer& allPlayers,
		const spd::param::Parameter& param,
		int step) const {

		int core = param.getCore();
		std::vector<std::thread> thr(core);

		// 順番に処理
		for (auto& rule : rulesAfterOutput) {

			// 1コアが担当するプレイヤ数
			int playerNum = allPlayers.size();
			int breadth = playerNum / core;

			for (int i = 0, size = thr.size(); i < size; ++i) {
				thr[i] = std::thread(
						[&, i]{

					int from = breadth * i;
					int to = (i + 1 < core) ? breadth * (i + 1) : playerNum;
					for (int id = from; id < to; ++id) {
						rule->runRule(allPlayers[id], allPlayers, param, step);
					}
				}
				);
			}

			for (std::thread& t : thr) {
				t.join();
			}
		}
	}
Esempio n. 18
0
 inline void joinThreads() const
 {
     while (!thr()->empty()) {
         driver->runningThreads.front()->join();
         unregisterThread(driver->runningThreads.front());
     }
 }
Esempio n. 19
0
int my_main(int argc, char *argv[]) {
  std::string configFileName;
  int ch;
  while ((ch = slib::getopt(argc, argv, "dhf:")) != -1) {
    switch (ch) {
    case 'f':
      configFileName = slib::optarg;
      if (!CONFIG->parseFromFile(configFileName)){
        std::cout << "load config file fail\n";
        return -1;
      }
      break;
    case 'd':
      CONFIG->enableEventDebug = true;
      break;
    case 'h':
    case '?':
    default:
      usage();
      return -1;
    }
  }
  MYDEBUG("start");
  std::shared_ptr<IRunnable> r=std::make_shared<LibeventThread>();
  MyThread thr(r);
  thr.run();
  unsigned ret=thr.wait();
  return ret;
}
Esempio n. 20
0
        virtual void accepted(MessagingPort * p) {

            if ( ! connTicketHolder.tryAcquire() ) {
                log() << "connection refused because too many open connections: " << connTicketHolder.used() << endl;

                // TODO: would be nice if we notified them...
                p->shutdown();
                delete p;

                sleepmillis(2); // otherwise we'll hard loop
                return;
            }

            try {
                boost::thread thr( boost::bind( &pms::threadRun , p ) );
            }
            catch ( boost::thread_resource_error& ) {
                connTicketHolder.release();
                log() << "can't create new thread, closing connection" << endl;

                p->shutdown();
                delete p;

                sleepmillis(2);
            }
        }
Esempio n. 21
0
 inline void registerThread(yarp::os::Thread *thread) const
 {
     reg_sem()->wait();
     lst_sem()->wait();
     thr()->push_back(thread);
     reg_sem()->post();
     lst_sem()->post();
 }
Esempio n. 22
0
void run() {
  try {
    thr(10);
    abort();
  } catch(const TestException &e) {
    caught = true;
  }
}
Esempio n. 23
0
        virtual void accepted(MessagingPort * p) {

            if ( ! connTicketHolder.tryAcquire() ) {
                log() << "connection refused because too many open connections: " << connTicketHolder.used() << endl;

                // TODO: would be nice if we notified them...
                p->shutdown();
                delete p;

                sleepmillis(2); // otherwise we'll hard loop
                return;
            }

            try {
#ifndef __linux__  // TODO: consider making this ifdef _WIN32
                boost::thread thr( boost::bind( &pms::threadRun , p ) );
#else
                pthread_attr_t attrs;
                pthread_attr_init(&attrs);
                pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);

                static const size_t STACK_SIZE = 1024*1024;
                pthread_attr_setstacksize(&attrs, (DEBUG_BUILD 
                                                    ? (STACK_SIZE / 2)
                                                    : STACK_SIZE));

                pthread_t thread;
                int failed = pthread_create(&thread, &attrs, (void*(*)(void*)) &pms::threadRun, p);

                pthread_attr_destroy(&attrs);

                if (failed) {
                    log() << "pthread_create failed: " << errnoWithDescription(failed) << endl;
                    throw boost::thread_resource_error(); // for consistency with boost::thread
                }
#endif
            }
            catch ( boost::thread_resource_error& ) {
                connTicketHolder.release();
                log() << "can't create new thread, closing connection" << endl;

                p->shutdown();
                delete p;

                sleepmillis(2);
            }
            catch ( ... ) {
                connTicketHolder.release();
                log() << "unknown error accepting new socket" << endl;

                p->shutdown();
                delete p;

                sleepmillis(2);
            }

        }
Esempio n. 24
0
int main()
{
    boost::timer timer;

    std::cout <<
        "This test tries to trigger a mythic race condition in the engine.\n"
        "Purportedly, the creature was witnessed and killed a couple of\n"
        "times before, but new sightings are reported every now and then.\n\n"

        "This test is here as a reminder to the adventurous!...\n\n\n"
        << std::flush;

    std::cout
        << "Starting background thread with race trigger.\n"
        << std::flush;

    boost::thread thr(race_trigger);

    {
        boost::xtime t;
        boost::xtime_get(&t, boost::TIME_UTC);

        std::cout
            << "Giving the trigger some time to work its magic.\n"
            << std::flush;

        t.sec += 58;
        boost::thread::sleep(t);

        std::cout
            << "Alright, that's enough!\n"
            << std::flush;

        run_trigger = false;

        std::cout
            << "... waiting for background thread to exit gracefully.\n"
            << std::flush;

        t.sec += 2;
        boost::thread::sleep(t);
    }

    std::cout
        << "That's it. We're out of here.\n\n"
        << std::flush;

    // Don't join the thread, it must be killed if it didn't complete in the
    // allotted time.

    std::cout
        << " === "
        << loop_count << " iterations in "
        << timer.elapsed() << " seconds.\n" << std::flush;

    exit(!graceful_exit);
}
int main(int argc, char* argv[])
{

bool use_window = true;

std::string SDF_filepath;
if(argc>=2){
  SDF_filepath = argv[1];
  if (argc>=3 && strcmp(argv[2], "--no-window") == 0) {
    use_window = false;
  } else {
    std::cout << "ERROR: unknown flag '" << argv[2] << "'" << std::endl;
  }
}
else{
  std::cout<<"ERROR: no File to be opened"<<std::endl;
  return 0;
}

  SDFReader reader(SDF_filepath);
  bool read = reader.load();

  Scene scene = reader.scene();

  std::shared_ptr<Renderer> app = reader.renderer();

  std::thread thr([&app]() {
    auto begin = std::chrono::high_resolution_clock::now();
    app->render(); 
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end-begin).count();
    std::cout << "rendered frame in " << duration << "ms" << std::endl;
  });

  if (use_window) {

    Window win(app->dimension());
    



    while (!win.shouldClose()) {
      if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {
        win.stop();
      }

      glDrawPixels( app->dimension().x, app->dimension().y, GL_RGB, GL_FLOAT
          , app->colorbuffer().data());

      win.update();
    }
  }

  thr.join();
  return 0;
}
Esempio n. 26
0
 void run_async() const {
   auto promise = std::promise<std::string>();
   std::thread thr([&]() {
     async_cb(callback(promise));
   });
   auto future = promise.get_future();
   auto ret = future.get();
   thr.join();
   ut_assert(ret.empty(), ret);
 }
Esempio n. 27
0
int main(int argc, char* argv[])
{
	Logger::setLogLevel(Logger::DEBUG);

	EventLoop loop;
	loop.runAfter(3.0, boost::bind(&EventLoop::quit, &loop));
	Thread thr(boost::bind(threadFunc, &loop));
	thr.start();
	loop.loop();
}
Esempio n. 28
0
void thr(int n) {
  if( --n <= 0 ) {
    thrown = true;
    throw TestException();
    abort();
  }

  Z z;
  thr(n - 1);
}
Esempio n. 29
0
void
CPoolOfThreads_ForServer::Spawn(unsigned int num_threads)
{
    for (unsigned int i = 0; i < num_threads; i++)
    {
        CRef<TThread> thr(NewThread());
        thr->CountSelf();
        thr->Run();
    }
}
Esempio n. 30
0
void QtiTimerManager::
start()
{
  std::cout << "QtiTimerManager::start" << std::endl;
  if (!_inSimulation)
  {
    std::thread thr(&QtiTimerManager::run, this);
    thr.join();
  }
}