Ejemplo n.º 1
0
bool setThreadName(pthread_t pid, StringPiece name) {
#if _WIN32
  static_assert(
      sizeof(unsigned int) == sizeof(std::thread::id),
      "This assumes std::thread::id is a thin wrapper around "
      "the thread id as an unsigned int, but that doesn't appear to be true.");

  // std::thread::id is a thin wrapper around an integral thread id,
  // so just stick the ID in.
  unsigned int tid = pthread_getw32threadid_np(pid);
  std::thread::id id;
  std::memcpy(&id, &tid, sizeof(id));
  return setThreadName(id, name);
#else
  static_assert(
      std::is_same<pthread_t, std::thread::native_handle_type>::value,
      "This assumes that the native handle type is pthread_t");
  static_assert(
      sizeof(std::thread::native_handle_type) == sizeof(std::thread::id),
      "This assumes std::thread::id is a thin wrapper around "
      "std::thread::native_handle_type, but that doesn't appear to be true.");
  // In most implementations, std::thread::id is a thin wrapper around
  // std::thread::native_handle_type, which means we can do unsafe things to
  // extract it.
  std::thread::id id;
  std::memcpy(static_cast<void*>(&id), &pid, sizeof(id));
  return setThreadName(id, name);
#endif
}
AREXPORT 
ArRecurrentTask::ArRecurrentTask()
{
  setThreadName("ArRecurrentTask");
  running = go_req = killed = false;
  create();			// create the thread
}
Ejemplo n.º 3
0
Status TransportLayerASIO::start() {
    stdx::lock_guard<stdx::mutex> lk(_mutex);
    _running.store(true);

    // If we're in async mode then the ServiceExecutor will handle calling run_one() in a pool
    // of threads. Otherwise we need a thread to just handle the async_accept calls.
    if (!_listenerOptions.async) {
        _listenerThread = stdx::thread([this] {
            setThreadName("listener");
            while (_running.load()) {
                try {
                    _ioContext->run();
                    _ioContext->reset();
                } catch (...) {
                    severe() << "Uncaught exception in the listener: " << exceptionToStatus();
                    fassertFailed(40491);
                }
            }
        });
    }

    for (auto& acceptor : _acceptors) {
        acceptor.listen();
        _acceptConnection(acceptor);
    }

    return Status::OK();
}
Ejemplo n.º 4
0
void MetricsTransmitter::run()
{
    const auto & config = context.getConfigRef();
    auto interval = config.getInt(config_name + ".interval", 60);

    const std::string thread_name = "MericsTrns " + std::to_string(interval) + "s";
    setThreadName(thread_name.c_str());

    const auto get_next_time = [](size_t seconds)
    {
        /// To avoid time drift and transmit values exactly each interval:
        ///  next time aligned to system seconds
        /// (60s -> every minute at 00 seconds, 5s -> every minute:[00, 05, 15 ... 55]s, 3600 -> every hour:00:00
        return std::chrono::system_clock::time_point(
            (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()) / seconds) * seconds
            + std::chrono::seconds(seconds));
    };

    std::vector<ProfileEvents::Count> prev_counters(ProfileEvents::end());

    std::unique_lock lock{mutex};

    while (true)
    {
        if (cond.wait_until(lock, get_next_time(interval), [this] { return quit; }))
            break;

        transmit(prev_counters);
    }
}
void ofxThreadedYouTubeVideo::threadedFunction()
{
    setThreadName("ofxThreadedYouTubeVideo " + ofToString(thread.get_id()));

	while( isThreadRunning() ) {

       ofYouTubeLoaderEntry entry;
       while( urls_to_load.receive(entry) ) {

            if(!getNewURL(entry)) {
                ofLogError("ofxThreadedYouTubeVideo") << "couldn't load url: \"" << entry.input_url << "\"";
                //get another random video and try again
                loadYouTubeURL("",entry.id);
            }
            else {
                cout << "ofxThreadedYouTubeVideo got video url: " << entry.url << endl;
                ofVideoPlayer* vid = new ofVideoPlayer();
                vid->setUseTexture(false);
                vid->load(entry.url);
                ofxYouTubeURLEvent e = ofxYouTubeURLEvent(entry.url, entry.id,vid);
                ofNotifyEvent(youTubeURLEvent, e, this);
            }



        }

    } //is thread running
}
Ejemplo n.º 6
0
void CClient::waitForMoveAndSend(PlayerColor color)
{
	try
	{
		setThreadName("CClient::waitForMoveAndSend");
		assert(vstd::contains(battleints, color));
		BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
		if(ba.actionType != Battle::CANCEL)
		{
			logNetwork->traceStream() << "Send battle action to server: " << ba;
			MakeAction temp_action(ba);
			sendRequest(&temp_action, color);
		}
		return;
	}
	catch(boost::thread_interrupted&)
	{
        logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
		return;
	}
	catch(...)
	{
		handleException();
		return;
	}
    logNetwork->errorStream() << "We should not be here!";
}
void AsynchronousBlockInputStream::next()
{
    ready.reset();

    pool.schedule([this, thread_group = CurrentThread::getGroup()] ()
    {
        CurrentMetrics::Increment metric_increment{CurrentMetrics::QueryThread};

        try
        {
            if (first)
                setThreadName("AsyncBlockInput");

            /// AsynchronousBlockInputStream is used in Client which does not create queries and thread groups
            if (thread_group)
                CurrentThread::attachToIfDetached(thread_group);
        }
        catch (...)
        {
            exception = std::current_exception();
            ready.set();
            return;
        }

        calculate();
    });
}
Ejemplo n.º 8
0
int CConsoleHandler::run()
{
	setThreadName("CConsoleHandler::run");
	//disabling sync to make in_avail() work (othervice always returns 0)
	std::ios::sync_with_stdio(false);
	std::string buffer;

	while ( std::cin.good() )
	{
#ifndef _WIN32
		//check if we have some unreaded symbols
		if (std::cin.rdbuf()->in_avail())
		{
			if ( getline(std::cin, buffer).good() )
				if ( cb && *cb )
					(*cb)(buffer);
		}
		else
			boost::this_thread::sleep(boost::posix_time::millisec(100));

		boost::this_thread::interruption_point();
#else
		std::getline(std::cin, buffer);
		if ( cb && *cb )
			(*cb)(buffer);
#endif
	}
	return -1;
}
Ejemplo n.º 9
0
    // Background object can be only be destroyed after jobBody() ran
    void BackgroundJob::jobBody( boost::shared_ptr<JobStatus> status ) {
        LOG(1) << "BackgroundJob starting: " << name() << endl;
        {
            scoped_lock l( status->m );
            massert( 13643 , mongoutils::str::stream() << "backgroundjob already started: " << name() , status->state == NotStarted );
            status->state = Running;
        }

        const string threadName = name();
        if( ! threadName.empty() )
            setThreadName( threadName.c_str() );

        try {
            run();
        }
        catch ( std::exception& e ) {
            log( LL_ERROR ) << "backgroundjob " << name() << "error: " << e.what() << endl;
        }
        catch(...) {
            log( LL_ERROR ) << "uncaught exception in BackgroundJob " << name() << endl;
        }

        {
            scoped_lock l( status->m );
            status->state = Done;
            status->finished.notify_all();
        }

        if( status->deleteSelf )
            delete this;
    }
Ejemplo n.º 10
0
void BackgroundJob::jobBody() {
    const string threadName = name();
    if (!threadName.empty()) {
        setThreadName(threadName);
    }

    LOG(1) << "BackgroundJob starting: " << threadName;

    try {
        run();
    } catch (const std::exception& e) {
        error() << "backgroundjob " << threadName << " exception: " << redact(e.what());
        throw;
    }

    // We must cache this value so that we can use it after we leave the following scope.
    const bool selfDelete = _selfDelete;

    {
        // It is illegal to access any state owned by this BackgroundJob after leaving this
        // scope, with the exception of the call to 'delete this' below.
        stdx::unique_lock<stdx::mutex> l(_status->mutex);
        _status->state = Done;
        _status->done.notify_all();
    }

    if (selfDelete)
        delete this;
}
Ejemplo n.º 11
0
    /**
     * This must be called whenever a new thread is started, so that active threads can be tracked
     * so each thread has a Client object in TLS.
     */
    void Client::initThread(const char *desc, AbstractMessagingPort *mp) {
        invariant(currentClient.get() == 0);

        string fullDesc;
        if (mp != NULL) {
            fullDesc = str::stream() << desc << mp->connectionId();
        }
        else {
            fullDesc = desc;
        }

        setThreadName(fullDesc.c_str());
        mongo::lastError.initThread();

        // Create the client obj, attach to thread
        Client* client = new Client(fullDesc, mp);
        client->setAuthorizationSession(
            new AuthorizationSession(
                new AuthzSessionExternalStateMongod(getGlobalAuthorizationManager())));

        currentClient.reset(client);

        // This makes the client visible to maintenance threads
        boost::lock_guard<boost::mutex> clientLock(clientsMutex);
        clients.insert(client);
    }
Ejemplo n.º 12
0
        void threadRun( MessagingPort * inPort) {
            TicketHolderReleaser connTicketReleaser( &connTicketHolder );

            setThreadName( "conn" );
            
            assert( inPort );
            inPort->setLogLevel(1);
            scoped_ptr<MessagingPort> p( inPort );

            p->postFork();

            string otherSide;

            Message m;
            try {
                LastError * le = new LastError();
                lastError.reset( le ); // lastError now has ownership

                otherSide = p->remoteString();

                handler->connected( p.get() );

                while ( ! inShutdown() ) {
                    m.reset();
                    p->clearCounters();

                    if ( ! p->recv(m) ) {
                        if( !cmdLine.quiet )
                            log() << "end connection " << otherSide << endl;
                        p->shutdown();
                        break;
                    }

                    handler->process( m , p.get() , le );
                    networkCounter.hit( p->getBytesIn() , p->getBytesOut() );
                }
            }
            catch ( AssertionException& e ) {
                log() << "AssertionException handling request, closing client connection: " << e << endl;
                p->shutdown();
            }
            catch ( SocketException& e ) {
                log() << "SocketException handling request, closing client connection: " << e << endl;
                p->shutdown();
            }
            catch ( const ClockSkewException & ) {
                log() << "ClockSkewException - shutting down" << endl;
                exitCleanly( EXIT_CLOCK_SKEW );
            }
            catch ( std::exception &e ) {
                error() << "Uncaught std::exception: " << e.what() << ", terminating" << endl;
                dbexit( EXIT_UNCAUGHT );
            }
            catch ( ... ) {
                error() << "Uncaught exception, terminating" << endl;
                dbexit( EXIT_UNCAUGHT );
            }

            handler->disconnected( p.get() );
        }
Ejemplo n.º 13
0
void AsynchronousMetrics::run()
{
    setThreadName("AsyncMetrics");

    std::unique_lock<std::mutex> lock{wait_mutex};

    /// Next minute + 30 seconds. To be distant with moment of transmission of metrics, see MetricsTransmitter.
    const auto get_next_minute = []
    {
        return std::chrono::time_point_cast<std::chrono::minutes, std::chrono::system_clock>(
            std::chrono::system_clock::now() + std::chrono::minutes(1)) + std::chrono::seconds(30);
    };

    while (true)
    {
        if (wait_cond.wait_until(lock, get_next_minute(), [this] { return quit; }))
            break;

        try
        {
            update();
        }
        catch (...)
        {
            tryLogCurrentException(__PRETTY_FUNCTION__);
        }
    }
}
Ejemplo n.º 14
0
 explicit Log( std::ostream& stream )
     : _indent(0), _blocked(0), _noHeader(0),
       _newLine(true), _stream(stream)
 {
     _file[0] = 0;
     setThreadName( "Unknown" );
 }
void ofxMtJsonParser::threadedFunction(){

	#if( OF_VERSION_MINOR <= 9 )
	try {
		getPocoThread().setName("ofxMtJsonParser");
		getPocoThread().setOSPriority(Poco::Thread::getMinOSPriority());
	} catch (Poco::SystemException exc) {
		ofLogError("ofxMtJsonParser") << exc.what() << " " << exc.message() << " " << exc.displayText();
	}
	#else
	setThreadName("ofxMtJsonParser");
	#endif

	switch (state) {
		case CHECKING_JSON:
			checkLocalJsonAndSplitWorkload();
			ofSleepMillis(16);
			break;

		case MERGE_THREAD_RESULTS:
			mergeThreadResults();
			ofSleepMillis(16);
			break;

		default: break;
	}
}
// a nice simple constructor
Joydrive::Joydrive(ArRobot *robot)
{
  setThreadName("Joydrive");
  // set the robot pointer
  myRobot = robot;
  // initialize the joystick
  myJoyHandler.init();
  // set up the joystick so we'll get the speeds out we want
  myJoyHandler.setSpeeds(40, 700);

  // see if we have a joystick, and let the users know
  if (myJoyHandler.haveJoystick())
  {
    printf("Have a joystick\n\n");
  }
  // if we don't have a joystick, then print error message and exit
  else
  {
    printf("Do not have a joystick, set up the joystick then rerun the program\n\n");
    Aria::exit(1);  // exit program with error code 1
  }

  // this is what creates are own thread, its from the ArASyncTask
  create();
}
Ejemplo n.º 17
0
void BaseThread::doRun()
{
	m_pPrivates->m_bIsRunning = true;
	applyPriority();
	setThreadName();
	run();
}
Ejemplo n.º 18
0
void CClient::run()
{
	setThreadName("CClient::run");
	try
	{
		while(!terminate)
		{
			CPack *pack = serv->retreivePack(); //get the package from the server
			
			if (terminate) 
			{
				vstd::clear_pointer(pack);
				break;
			}

			handlePack(pack);
		}
	} 
	//catch only asio exceptions
	catch (const boost::system::system_error& e)
	{	
        logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
        logNetwork->errorStream() << e.what();
		if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
		{
            logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
			throw;
		}
	}
}
Ejemplo n.º 19
0
TrackScheduler::TrackScheduler(const TrackerParamsProviderBasePtr& paramsProvider)
: GenericSchedulerThread()
, _imp( new TrackSchedulerPrivate(paramsProvider) )
{
    QObject::connect( this, SIGNAL(renderCurrentFrameForViewer(ViewerInstancePtr)), this, SLOT(doRenderCurrentFrameForViewer(ViewerInstancePtr)) );

    setThreadName("TrackScheduler");
}
Ejemplo n.º 20
0
 Client& Client::initThread(const char *desc, AbstractMessagingPort *mp) {
     setThreadName(desc);
     assert( currentClient.get() == 0 );
     Client *c = new Client(desc, mp);
     currentClient.reset(c);
     mongo::lastError.initThread();
     return *c;
 }
Ejemplo n.º 21
0
AREXPORT ArSyncLoop::ArSyncLoop() :
  ArASyncTask(),
  myStopRunIfNotConnected(false),
  myRobot(0)
{
  setThreadName("ArSyncLoop");
  myInRun = false;
}
Ejemplo n.º 22
0
 Client& Client::initThread(const char *desc, AbstractMessagingPort *mp) {
     DEV nThreads++; // never decremented.  this is for casi class asserts
     setThreadName(desc);
     verify( currentClient.get() == 0 );
     Client *c = new Client(desc, mp);
     currentClient.reset(c);
     mongo::lastError.initThread();
     return *c;
 }
Ejemplo n.º 23
0
void EventBase::setName(const std::string& name) {
  assert(isInEventBaseThread());
  name_ = name;

  if (isRunning()) {
    setThreadName(loopThread_.load(std::memory_order_relaxed),
                  name_);
  }
}
Ejemplo n.º 24
0
 Client& Client::initThread(const char *desc, AbstractMessagingPort *mp) {
     // mp is non-null only for client connections, and mongos uses ClientInfo for those
     massert(16478, "Mongos Client being used for incoming connection thread", mp == NULL);
     setThreadName(desc);
     verify( currentClient.get() == 0 );
     Client *c = new Client(desc, mp);
     currentClient.reset(c);
     mongo::lastError.initThread();
     return *c;
 }
Ejemplo n.º 25
0
    /* resets the client for the current thread */
    void Client::resetThread( const StringData& origThreadName ) {
        verify( currentClient.get() != 0 );

        // Detach all client info from thread
        mongo::lastError.reset(NULL);
        currentClient.get()->shutdown();
        currentClient.reset(NULL);

        setThreadName( origThreadName.rawData() );
    }
Ejemplo n.º 26
0
void initializeThreading()
{
    if (!atomicallyInitializedStaticMutex) {
        atomicallyInitializedStaticMutex = new Mutex;
        threadMapMutex();
        wtf_random_init();
        initializeMainThread();
        mainThreadIdentifier = currentThread();
        setThreadName(mainThreadIdentifier, "Main Thread");
    }
}
Ejemplo n.º 27
0
void cpuManager_setThreadName(ObjectDesc * self, ObjectDesc * name)
{
	char value[128];
	if (name == NULL)
		return;
	stringToChar(name, value, sizeof(value));

	DISABLE_IRQ;
	setThreadName(curthr(), value, "");
	RESTORE_IRQ;
}
Ejemplo n.º 28
0
    void start( const MessageServer::Options& opts ) {
        setThreadName( "mongosMain" );

        balancer.go();
        cursorCache.startTimeoutThread();
        PeriodicTask::theRunner->go();

        ShardedMessageHandler handler;
        MessageServer * server = createServer( opts , &handler );
        server->setAsTimeTracker();
        server->run();
    }
Ejemplo n.º 29
0
ArCentralManager::ArCentralManager() : 
  myNetSwitchCB(this, &ArCentralManager::netServerSwitch),
  myNetClientListCB(this, &ArCentralManager::netClientList),
  myAriaExitCB(this, &ArCentralManager::close),
  myProcessFileCB(this, &ArCentralManager::processFile),
  myForwarderServerClientRemovedCB(
	  this, &ArCentralManager::forwarderServerClientRemovedCallback),
  myMainServerClientRemovedCB(
	  this, &ArCentralManager::mainServerClientRemovedCallback)
{
  myMutex.setLogName("ArCentralManager::myCallbackMutex");
  myDataMutex.setLogName("ArCentralManager::myDataMutex");
  setThreadName("ArCentralManager");

  myTimeChecker.setName("ArCentralManager");
  myTimeChecker.setDefaultMSecs(100);

  myRobotServer = NULL;
  myClientServer = NULL;

  myLoopMSecs = 1;
  /*
  Aria::getConfig()->addParam(
	  ArConfigArg("ArCentralManager_MSecToSleepInLoop",
		      &myLoopMSecs,
		      "The number of MS to sleep in the loop (default 1)", 1),
	  "Misc Testing", 
	  ArPriority::EXPERT);
  */

  myAriaExitCB.setName("ArCentralManager");
  Aria::addExitCallback(&myAriaExitCB, 25);

  myEnforceType = ArServerCommands::TYPE_UNSPECIFIED;

  
  /*  I don't think we need this one
  myRobotServer->addData("centralServerHeartbeat", "Just a data to let the robot's know that this server has the centralServerHeartbeat feature (nothing is actually done with this command)",
			 NULL, "none", "none", "RobotInfo", 
			 "RETURN_NONE");
  */

  myClosingConnectionID = 0;

  myMostForwarders = 0;
  myMostClients = 0;

  myForwarderServerClientRemovedCB.setName("ArCentralManager");


  myMainServerClientRemovedCB.setName("ArCentralManager");
}
Ejemplo n.º 30
0
VoxPlayer::VoxPlayer()
{
    pthread_mutex_init(&m_cs, NULL);

    mpg123_init();
    ao_initialize();

    m_playpath = "";
    m_isplaying = false;
    m_interrupt = false;

    setThreadName("PLAY");
}