#include <iostream>
#include <thread>
#include <unistd.h>
#include <mutex>
#include <condition_variable>
/**
 * 览辉视频封装接口
 */
class LHAVObject {
private:
    bool m_bIsRelease = false;
public:
    std::mutex m_oWorkingMutex;
    std::condition_variable m_nWaitWorkingCV; //推流消费条件锁
    int m_bIsWorking = 0;
public:
    /**
     * 释放标记
     * @return
     */
    bool IsRelease() { return m_bIsRelease; }
    /**
     * 释放资源
     * @return
     */
    bool Release() { return true; }
    /**
     * 验证释放
     */
    bool ValidRelease() {
        std::unique_lock<std::mutex> lock(this->m_oWorkingMutex); //释放标记锁
        this->m_bIsRelease = true; //标记释放
        for (int i = 0; i <= 20 && this->m_bIsWorking >= 1; i++) { //检测是否有工作正在进行
            if (i >= 20) {
                this->m_bIsRelease = false; //释放失败
                return false;
            }
            m_nWaitWorkingCV.wait(lock);
        }
        return true;
    }
};
class FunMarker {
public:
    explicit FunMarker(LHAVObject *o) {
        this->m_pObject = o;
        if (this->m_pObject == nullptr) { return; }
        std::unique_lock<std::mutex> lock(this->m_pObject->m_oWorkingMutex); //释放标记锁
        this->m_pObject->m_bIsWorking++;
    }
    virtual ~FunMarker() {
        if (this->m_pObject == nullptr) { return; }
        std::unique_lock<std::mutex> lock(this->m_pObject->m_oWorkingMutex); //释放标记锁
        this->m_pObject->m_bIsWorking--;
        this->m_pObject->m_nWaitWorkingCV.notify_all();
    }
private:
    LHAVObject *m_pObject;
};
class Student : public LHAVObject {
public:
    bool isWorking = false;
public:
    void Hello() {
        FunMarker maker(this);
        isWorking = true;
        sleep(20);
        std::cout << "hello" << std::endl;
        isWorking = false;
    }
};
int main() {
    std::cout << "Hello, World!" << std::endl;
    auto *b = new Student();
    std::thread test([](Student *c) {
        c->Hello();
    }, b);
    test.detach();
    if(!b->ValidRelease()){
        return 0;
    }
    b->Release();
    delete b;
    std::cout << "Hello, World!3" << std::endl;
    return 0;
}