Example #1
0
void ThreadPool::startThinking(
  const Position& pos,
  const LimitsType& limits,
  const std::vector<Move>& searchMoves,
  const std::chrono::time_point<std::chrono::system_clock>& goReceivedTime)
{
  waitForThinkFinished();
  pos.searcher()->searchTimer.set(goReceivedTime);

  pos.searcher()->signals.stopOnPonderHit = pos.searcher()->signals.firstRootMove = false;
  pos.searcher()->signals.stop = pos.searcher()->signals.failedLowAtRoot = false;

  pos.searcher()->rootPosition = pos;
  pos.searcher()->limits.set(limits);
  pos.searcher()->rootMoves.clear();

#if defined LEARN
  const MoveType MT = LegalAll;
#else
  const MoveType MT = Legal;
#endif

  for (MoveList<MT> ml(pos); !ml.end(); ++ml) {
    if (searchMoves.empty()
      || std::find(searchMoves.begin(), searchMoves.end(), ml.move()) != searchMoves.end())
    {
      pos.searcher()->rootMoves.push_back(RootMove(ml.move()));
    }
  }

  mainThread()->thinking = true;
  mainThread()->notifyOne();
}
Example #2
0
    void EngineMain::run(const bpo::variables_map& variables)
    {
        Settings::Settings settings;
        if(!settings.loadUserSettings())
            return;

        size_t resolutionWidth = settings.get<size_t>("Display","resolutionWidth");
        size_t resolutionHeight = settings.get<size_t>("Display","resolutionHeight");
        bool fullscreen = settings.get<size_t>("Display", "fullscreen");
        std::string pathEXE = settings.get<std::string>("Game", "PathEXE");
        if (pathEXE == "")
        {
            pathEXE = "Diablo.exe";
        }

        Engine::ThreadManager threadManager;
        FARender::Renderer renderer(resolutionWidth, resolutionHeight, fullscreen);

        mInputManager = new EngineInputManager(*this);

        std::thread mainThread(boost::bind(&EngineMain::runGameLoop, this, &variables, pathEXE));

        threadManager.run();
        renderDone = true;

        mainThread.join();
    }
Example #3
0
    void EngineMain::run(const bpo::variables_map& variables)
    {
        Settings::Settings settings;
        if(!settings.loadUserSettings())
            return;

        size_t resolutionWidth = settings.get<size_t>("Display","resolutionWidth");
        size_t resolutionHeight = settings.get<size_t>("Display","resolutionHeight");
        std::string fullscreen = settings.get<std::string>("Display", "fullscreen");
        std::string pathEXE = settings.get<std::string>("Game", "PathEXE");
        if (pathEXE == "")
        {
            pathEXE = "Diablo.exe";
        }

        Engine::ThreadManager threadManager;
        FARender::Renderer renderer(resolutionWidth, resolutionHeight, fullscreen == "true");
        mInputManager = std::make_shared<EngineInputManager>(renderer.getNuklearContext());
        mInputManager->registerKeyboardObserver(this);
        std::thread mainThread(std::bind(&EngineMain::runGameLoop, this, &variables, pathEXE));
        threadManager.run();
        renderDone = true;

        mainThread.join();
    }
Example #4
0
int main()
{
	struct sockaddr_in servaddr;

	sockfd=socket(AF_INET,SOCK_STREAM,0);

	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_addr.s_addr=inet_addr("114.212.142.70");
	servaddr.sin_port=htons(SERV_PORT);

	local_log=0;

	if(connect(sockfd,(struct sockaddr *)&servaddr ,sizeof(servaddr))==0)
		{
			printf("%s\n","Connect succeed" );
			int tag2=pthread_create(&recv_thread,NULL,recvThread,NULL);
				if(tag2!=0)
					printf("%s\n","thread recv create error!" );
			mainThread(NULL);
		}
	else
		printf("%s\n","Connect failed" );

	return 0;
}
Example #5
0
int main(int argc, char** argv)
{
    boost::thread mainThread(boost::bind(&realmain, argc, argv));
    Input::InputManager input(&keyPress, NULL, &mouseClick, &mouseRelease, &mouseMove);
    FARender::Renderer renderer;
    renderDone = true;

    mainThread.join();
}
Example #6
0
void run(const bpo::variables_map& variables)
{
    StartupSettings settings;
    if (!loadSettings(settings))
        return;

    boost::thread mainThread(boost::bind(&runGameLoop, &variables));

    FARender::Renderer renderer(settings.resolutionWidth, settings.resolutionHeight);
    renderDone = true;

    mainThread.join();
}
Example #7
0
void ThreadPool::startThinking(const Position& pos, const LimitsType& limits,
							   const std::vector<Move>& searchMoves)
{
#if defined LEARN
#else
	waitForThinkFinished();
#endif
	pos.searcher()->searchTimer.restart();

	pos.searcher()->signals.stopOnPonderHit = pos.searcher()->signals.firstRootMove = false;
	pos.searcher()->signals.stop = pos.searcher()->signals.failedLowAtRoot = false;

	pos.searcher()->rootPosition = pos;
	pos.searcher()->limits = limits;
	pos.searcher()->rootMoves.clear();

#if defined LEARN
	// searchMoves を直接使う。
	pos.searcher()->rootMoves.push_back(RootMove(searchMoves[0]));
#else
	const MoveType MT = Legal;
	for (MoveList<MT> ml(pos); !ml.end(); ++ml) {
		if (searchMoves.empty()
			|| std::find(searchMoves.begin(), searchMoves.end(), ml.move()) != searchMoves.end())
		{
			pos.searcher()->rootMoves.push_back(RootMove(ml.move()));
		}
	}
#endif

#if defined LEARN
	// 浅い探索なので、thread 生成、破棄のコストが高い。余分な thread を生成せずに直接探索を呼び出す。
	pos.searcher()->think();
#else
	mainThread()->thinking = true;
	mainThread()->notifyOne();
#endif
}
Example #8
0
nsHTTPListener::~nsHTTPListener()
{
  if (mResponsibleForDoneSignal)
    send_done_signal();

  if (mCondition)
    PR_DestroyCondVar(mCondition);
  
  if (mLock)
    PR_DestroyLock(mLock);

  if (mLoader) {
    nsCOMPtr<nsIThread> mainThread(do_GetMainThread());
    NS_ProxyRelease(mainThread, mLoader);
  }
}
Example #9
0
void run(const bpo::variables_map& variables)
{
    StartupSettings settings;
    if (!loadSettings(settings))
        return;


    Engine::ThreadManager threadManager;
    FARender::Renderer renderer(settings.resolutionWidth, settings.resolutionHeight);

    Input::InputManager input(&keyPress, NULL, &mouseClick, &mouseRelease, &mouseMove, renderer.getRocketContext());

    boost::thread mainThread(boost::bind(&runGameLoop, &variables));

    threadManager.run();
    renderDone = true;

    mainThread.join();
}
Example #10
0
void ThreadPool::waitForThinkFinished() {
  MainThread* t = mainThread();
  std::unique_lock<std::mutex> lock(t->sleepLock);
  sleepCond_.wait(lock, [&] { return !(t->thinking); });
}
Example #11
0
int main()
{
    // Setup ROS Arguments
    char** argv = NULL;
    int argc = 0;

    // Init ROS Node
    ros::init(argc, argv, "RC_Main");
    ros::NodeHandle nh;
    ros::NodeHandle pNh("~");

    // Topic names
    std::string hmiConsolePub, grabService, getBricksService, plcService, anyBricksSub, safetySub, mesPub, mesSub, hmiStatusSub;
    pNh.param<std::string>("hmiConsole", hmiConsolePub, "/rcHMI/console");
    pNh.param<std::string>("grabService", grabService, "/rcGrasp/grabBrick");
    pNh.param<std::string>("getBricksService", getBricksService, "/rcVision/getBricks");
    pNh.param<std::string>("plcService", plcService, "/rcPLC");
    pNh.param<std::string>("anyBricks_sub", anyBricksSub, "/rcVision/anyBricks");
    pNh.param<std::string>("hmi_status_sub", hmiStatusSub, "/rcHMI/status");
    pNh.param<std::string>("mesPub", mesPub, "/rcMESClient/msgToServer");
    pNh.param<std::string>("mesSub", mesSub, "/rcMESClient/msgFromServer");

    // Create service calls
    _serviceGrabBrick = nh.serviceClient<rc_grasp::grabBrick>(grabService);
    _serviceGetBricks = nh.serviceClient<rc_vision::getBricks>(getBricksService);
    _serviceMove = nh.serviceClient<rc_plc::MoveConv>(plcService + "/MoveConv");
    _serviceStart = nh.serviceClient<rc_plc::StartConv>(plcService + "/StartConv");
    _serviceStop = nh.serviceClient<rc_plc::StopConv>(plcService + "/StopConv");
    _serviceChangeDir = nh.serviceClient<rc_plc::ChangeDirection>(plcService + "/ChangeDirection");
    _serviceGetIsMoving = nh.serviceClient<kuka_rsi::getIsMoving>("/KukaNode/IsMoving");
    _serviceGetConf = nh.serviceClient<kuka_rsi::getConfiguration>("/KukaNode/GetConfiguration");
    _serviceGetSafety = nh.serviceClient<kuka_rsi::getSafety>("/KukaNode/GetSafety");

    // Publishers
    _hmiConsolePub = nh.advertise<std_msgs::String>(hmiConsolePub, 100);
    _mesMessagePub = nh.advertise<std_msgs::String>(mesPub, 100);
    _mainStatusPub = nh.advertise<std_msgs::String>("/rcMain/status", 100);

    // Subscribers
    ros::Subscriber anyBrickSub = nh.subscribe(anyBricksSub, 10, anyBrickCallback);
    ros::Subscriber mesMessageSub = nh.subscribe(mesSub, 10, mesRecCallback);
    ros::Subscriber hmiStatusSubs = nh.subscribe(hmiStatusSub, 10, hmiStatusCallback);

    // Main handler thread
    boost::thread mainThread(mainHandlerThread);

    // Spin rate
    ros::Rate r(10); // 10 hz

    // Spin
    while(ros::ok())
    {
        // Get safety
        kuka_rsi::getSafety obj;
        _serviceGetSafety.call(obj);
        _safetyMutex.lock();
        _safety = obj.response.safetyBreached;
        _safetyMutex.unlock();

        ros::spinOnce();
        r.sleep();
    }

    // Return
   mainThread.interrupt();
    return 0;
}
int
LauncherMain(int argc, wchar_t* argv[])
{
  // Make sure that the launcher process itself has image load policies set
  if (IsWin10AnniversaryUpdateOrLater()) {
    const DynamicallyLinkedFunctionPtr<decltype(&SetProcessMitigationPolicy)>
      pSetProcessMitigationPolicy(L"kernel32.dll", "SetProcessMitigationPolicy");
    if (pSetProcessMitigationPolicy) {
      PROCESS_MITIGATION_IMAGE_LOAD_POLICY imgLoadPol = {};
      imgLoadPol.PreferSystem32Images = 1;

      DebugOnly<BOOL> setOk = pSetProcessMitigationPolicy(ProcessImageLoadPolicy,
                                                          &imgLoadPol,
                                                          sizeof(imgLoadPol));
      MOZ_ASSERT(setOk);
    }
  }

  if (!SetArgv0ToFullBinaryPath(argv)) {
    ShowError();
    return 1;
  }

  LauncherFlags flags = ProcessCmdLine(argc, argv);

  nsAutoHandle mediumIlToken;
  Maybe<ElevationState> elevationState = GetElevationState(flags, mediumIlToken);
  if (!elevationState) {
    return 1;
  }

  // If we're elevated, we should relaunch ourselves as a normal user.
  // Note that we only call LaunchUnelevated when we don't need to wait for the
  // browser process.
  if (elevationState.value() == ElevationState::eElevated &&
      !(flags & (LauncherFlags::eWaitForBrowser | LauncherFlags::eNoDeelevate)) &&
      !mediumIlToken.get()) {
    return !LaunchUnelevated(argc, argv);
  }

  // Now proceed with setting up the parameters for process creation
  UniquePtr<wchar_t[]> cmdLine(MakeCommandLine(argc, argv));
  if (!cmdLine) {
    return 1;
  }

  const Maybe<bool> isSafeMode = IsSafeModeRequested(argc, argv,
                                                     SafeModeFlag::NoKeyPressCheck);
  if (!isSafeMode) {
    ShowError(ERROR_INVALID_PARAMETER);
    return 1;
  }

  ProcThreadAttributes attrs;
  SetMitigationPolicies(attrs, isSafeMode.value());

  HANDLE stdHandles[] = {
    ::GetStdHandle(STD_INPUT_HANDLE),
    ::GetStdHandle(STD_OUTPUT_HANDLE),
    ::GetStdHandle(STD_ERROR_HANDLE)
  };

  attrs.AddInheritableHandles(stdHandles);

  DWORD creationFlags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT;

  STARTUPINFOEXW siex;
  Maybe<bool> attrsOk = attrs.AssignTo(siex);
  if (!attrsOk) {
    ShowError();
    return 1;
  }

  BOOL inheritHandles = FALSE;

  if (attrsOk.value()) {
    creationFlags |= EXTENDED_STARTUPINFO_PRESENT;

    if (attrs.HasInheritableHandles()) {
      siex.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
      siex.StartupInfo.hStdInput = stdHandles[0];
      siex.StartupInfo.hStdOutput = stdHandles[1];
      siex.StartupInfo.hStdError = stdHandles[2];

      // Since attrsOk == true, we have successfully set the handle inheritance
      // whitelist policy, so only the handles added to attrs will be inherited.
      inheritHandles = TRUE;
    }
  }

  PROCESS_INFORMATION pi = {};
  BOOL createOk;

  if (mediumIlToken.get()) {
    createOk = ::CreateProcessAsUserW(mediumIlToken.get(), argv[0], cmdLine.get(),
                                      nullptr, nullptr, inheritHandles,
                                      creationFlags, nullptr, nullptr,
                                      &siex.StartupInfo, &pi);
  } else {
    createOk = ::CreateProcessW(argv[0], cmdLine.get(), nullptr, nullptr,
                                inheritHandles, creationFlags, nullptr, nullptr,
                                &siex.StartupInfo, &pi);
  }

  if (!createOk) {
    ShowError();
    return 1;
  }

  nsAutoHandle process(pi.hProcess);
  nsAutoHandle mainThread(pi.hThread);

  if (!PostCreationSetup(process.get(), mainThread.get(), isSafeMode.value()) ||
      ::ResumeThread(mainThread.get()) == static_cast<DWORD>(-1)) {
    ShowError();
    ::TerminateProcess(process.get(), 1);
    return 1;
  }

  if (flags & LauncherFlags::eWaitForBrowser) {
    DWORD exitCode;
    if (::WaitForSingleObject(process.get(), INFINITE) == WAIT_OBJECT_0 &&
        ::GetExitCodeProcess(process.get(), &exitCode)) {
      // Propagate the browser process's exit code as our exit code.
      return static_cast<int>(exitCode);
    }
  } else {
    const DWORD timeout = ::IsDebuggerPresent() ? INFINITE :
                          kWaitForInputIdleTimeoutMS;

    // Keep the current process around until the callback process has created
    // its message queue, to avoid the launched process's windows being forced
    // into the background.
    mozilla::WaitForInputIdle(process.get(), timeout);
  }

  return 0;
}
Example #13
0
int main( int argc, char **argv )
{
    ChangeList::setReadWriteDefault();
    osgInit(argc,argv);

    _main_thread = Thread::getCurrent();
    _sync_barrier = Barrier::get("RenderBarrier");

    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication a( argc, argv );

    if(!QGLFormat::hasOpenGL())
    {
        qWarning( "This system has no OpenGL support. Exiting." );
        return -1;
    }
    
    _render_widget = new OpenSGWidget(QGLFormat(QGL::DoubleBuffer | QGL::DepthBuffer | QGL::Rgba |
                                      QGL::DirectRendering));

    NodePtr scene = makePlane(1.0, 1.0, 50, 50);

    MaterialChunkPtr matc = MaterialChunk::create();
    beginEditCP(matc);
        matc->setAmbient(Color4f(0.3, 0.3, 0.3, 1.0));
        matc->setDiffuse(Color4f(0.2, 0.2, 0.8, 1.0));
        matc->setSpecular(Color4f(0.6, 0.6, 0.6, 1.0));
        matc->setShininess(100);
    endEditCP(matc);
    
    ChunkMaterialPtr cmat = ChunkMaterial::create();
    beginEditCP(cmat);
        cmat->addChunk(matc);
    endEditCP(cmat);
    
    _geo = GeometryPtr::dcast(scene->getCore());
    beginEditCP(_geo);
        _geo->setDlistCache(false);
        _geo->setMaterial(cmat);
    endEditCP(_geo);

    initWave();
    resetWave();


    _render_widget->getManager()->setRoot(scene);
    _render_widget->getManager()->showAll();
    _render_widget->getManager()->getNavigator()->setFrom(Pnt3f(1.0f, -1.0f, 1.0f));
    _render_widget->getManager()->getNavigator()->setUp(Vec3f(0.0f, 0.0f, 1.0f));

    _render_widget->show();
    while(!_render_widget->isInitialized())
        qApp->processEvents();

    // The gl widget is initialized in the main thread!
    // Without the doneCurrent() the next makeCurrent() call in the render thread
    // doesn't work because qt thinks that the context is already current but this
    // was in the main thread ...
    _render_widget->doneCurrent();

    // start render thread
    _render_thread = dynamic_cast<Thread *>(ThreadManager::the()->getThread("RenderThread"));
    _render_thread->runFunction(renderThread, 1, NULL);
    
    // main loop
    while(!_quit)
    {
        mainThread();

        // sync
        _sync_barrier->enter(2);
        if(_do_quit)
            _quit = true;
        _sync_barrier->enter(2);
        
        _main_thread->getChangeList()->clearAll();

        qApp->processEvents();
    }

    Thread::join(_render_thread);
    return 0;
}
Example #14
0
File: Android.C Project: ansons/wt
    JNIEXPORT
    jint
    JNICALL
    Java_eu_webtoolkit_android_WtAndroid_startwt
    (JNIEnv* env, jobject thiz, jobjectArray strArray)
    {
        unsigned i;

        jsize argsCount = env->GetArrayLength(strArray);
        std::vector<std::string> args(argsCount);
        for (i = 0; i < argsCount; i++) {
            jstring jstr = (jstring)env->GetObjectArrayElement(strArray, i);
            std::string s = std::string(env->GetStringUTFChars(jstr, 0));
            env->DeleteLocalRef(jstr);

            if (boost::starts_with(s, "-D")) {
                std::string env = s.substr(2);
                size_t index = env.find("=");
                if (index != std::string::npos) {
                    if (!putenv(env.c_str()))
                        std::cerr
                                << "WtAndroid::startwt putenv() failed on: "
                                << env
                                << std::endl;
                } else {
                    std::cerr
                            << "WtAndroid::startwt invalid environment variable definition: "
                            << s
                            << std::endl;
                }
            } else {
                args.push_back(s);
            }
        }

        int argc = args.size();
        const char ** argv = new const char*[argc];
        for (i = 0; i < argc; i++) {
            argv[i] = args[i].c_str();
        }

        try {
            if (http::server::Server::instance())
                return http::server::Server::instance()->httpPort();
            boost::thread mainThread(&main, argc, argv);
            while (true) {
                if (http::server::Server::instance()) {
                    int httpPort = http::server::Server::instance()->httpPort();
                    if (httpPort != 0) {
                        http::server::Server::instance()->controller()->configuration()
                        .setSessionTimeout(-1);
                        return httpPort;
                    }
                }
                boost::this_thread::sleep(boost::posix_time::milliseconds(100));
            }
        } catch (Wt::WServer::Exception& e) {
            std::cerr << e.what() << "\n";
        } catch (std::exception& e) {
            std::cerr << "exception: " << e.what() << "\n";
        } catch (...) {
            std::cerr << "exception: " << "\n";
        }
    }