繁体   English   中英

C ++-如何使用Boost恢复线程?

[英]C++ - How do I revive a thread with boost?

摘要:客户端与其他用户一起位于Teamspeak服务器中。 当其他用户开始讲话时,此插件每500毫秒对用户运行一次setSpeakerPosition()函数,直到他们停止讲话为止。 如果他们再次讲话,就应该重新做一次。

问题:如果我每次他们讲话时都简单地执行.reset(new boost::thread(...)) ,似乎会覆盖现有线程(如果之前已经讲过)并导致崩溃。 我相信我需要“复兴”现有线程,或适当地杀死它。

// Create an array like: speakingThreads[client_id] = array(bIsSpeaking, ptrThread)
typedef boost::shared_ptr<boost::thread> SmartThread;
map<anyID, pair<bool, SmartThread>> speakingThreads;

// Called when someone starts or stops talking
void ts3plugin_onTalkStatusChangeEvent(uint64 serverConnectionHandlerID, int status, int isReceivedWhisper, anyID clientID) {

    // Get my client id
    anyID myID;
    ts3Functions.getClientID(serverConnectionHandlerID, &myID);

    // If someone else starts talking
    if(clientID != myID && status == STATUS_TALKING) {
        // Set client to 'is speaking' (allows thread loop to run)
        speakingThreads[clientID].first = true;

        // If this is the first time they have spoken, start a thread
        if(speakingThreads[clientID].second == NULL) {
            // Create thread to keep updating speaker position while he's speaking
            speakingThreads[clientID].second.reset(new boost::thread(speakerActiveThread, serverConnectionHandlerID, clientID));
            _log("Starting Thread", 0);
        }
        // Or if they've spoken before, revive the thread
        else {
            speakingThreads[clientID].second->speakerActiveThread(serverConnectionHandlerID, clientID); // error C2039: 'speakerActiveThread' : is not a member of 'boost::thread'
            _log("Reviving Thread", 0);
        }
    }
    // If someone else stops talking
    else if(clientID != myID && status == STATUS_NOT_TALKING) {
        if(speakingThreads.find(clientID) != speakingThreads.end()) {
            // Disable thread loop for the speaker to stop updating his position
            speakingThreads[clientID].first = false;
            _log("Interrupted Speaking Thread", 0);
        }
    }
}

// Thread run when someone starts speaking, loops until they finish speaking
void speakerActiveThread(uint64 serverConnectionHandlerID, anyID clientID) {
    // While client 'is speaking'
    while(speakingThreads[clientID].first) {
        if(setSpeakerPosition(serverConnectionHandlerID, clientID) != ERROR_ok) {
            _log("ERROR Setting Speaker Position", 1);
        }
        _log("Set Speaker Position", 0);
        Sleep(UPDATE_SPEAKER_MS); // 500
    }
}

您不能“重新启动”线程。 创建boost :: thread对象后,将要执行的线程函数传递给该对象,该函数在单独的OS线程中运行; 函数结束时-线程结束(退出)。 请注意,如果boost :: thread对象被破坏(例如,超出范围),则它不会影响线程本身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM