gpt4 book ai didi

c++ - 如何从自身加入 std::thread(在 C++11 中)

转载 作者:行者123 更新时间:2023-11-30 01:12:52 24 4
gpt4 key购买 nike

我有一个 std::thread 正在等待并从套接字读取数据。并且有一个指向此 thread 的指针存储在某处。但是当一些不好的事情发生并且 thread 结束时,我希望它调用一些东西来产生一个函数,这个函数将加入这个线程,然后删除引用它的指针。 (我可以从线程内访问该指针)

我可以在另一个线程中执行此操作,但那个新线程会成为问题。

最佳答案

您可以在分离状态下创建您的线程,并使您的线程生命周期依赖于一个条件变量,并在完成时切换一个 bool 状态。

#include <thread>
#include <iostream>
#include <unistd.h>
#include <condition_variable>
#include <mutex>

class A {
private:
void Threadfunction();
volatile bool class_running;
volatile bool thread_running;
std::condition_variable cv;
std::mutex mu;
public:
A();
~A();
void Stop();
};
A::A(){
class_running = true;
thread_running = false;
std::thread t(&A::Threadfunction,this);
t.detach();
}
A::~A(){
if(class_running) {this->Stop();}
}
void A::Stop() {
std::unique_lock<std::mutex> lk(mu);
class_running = false;
while(thread_running) {
cv.wait(lk);
}
std::cout << "Stop ended " << std::endl;
}
void A::Threadfunction(){
thread_running = true;
std::cout << "thread started " << std::endl;
while(class_running){
// Do something
}
thread_running = false;
cv.notify_one();
std::cout << "thread stopped " << std::endl;
}
int main(){
A a1;
A a2;
sleep(1);
std::cout << "a1.Stop() called " << std::endl;
a1.Stop();
sleep(1);
std::cout << "a2.Stop() not called but a2 goes out of scope and destructor is called " << std::endl;
}

关于c++ - 如何从自身加入 std::thread(在 C++11 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33312750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com