摘要:客户端与其他用户在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
}
}
答案 0 :(得分:0)
你不能“复活”线程。在创建了boost :: thread对象之后,向它传递一个你想要执行的线程函数,该函数在一个单独的OS线程中运行;当函数结束时 - 线程结束(退出)。请注意,如果boost :: thread对象被破坏(例如,超出范围),则不会影响线程本身。