C++三方服务异步拉起

发布于:2025-09-01 ⋅ 阅读:(19) ⋅ 点赞:(0)

Service.h

#pragma once
#include <string>

class ServiceCallback {
public:
    virtual void onSuccess() = 0;
    virtual void onFailure() = 0;
    virtual ~ServiceCallback() = default;
};

class Service {
public:
    Service();
    void start(ServiceCallback* callback); // 异步启动,回调通知成功/失败
    void sendMessage(const std::string& msg);
    void doSomethingElse();

private:
    bool started;
};

Service.cpp

#include "Service.h"
#include <thread>
#include <iostream>
#include <chrono>

Service::Service() : started(false) {}

void Service::start(ServiceCallback* callback) {
    std::thread([this, callback]() {
        std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟启动
        bool success = true; // 可以改成 false 模拟失败

        if (success) {
            started = true;
            std::cout << "Service started\n";
            if (callback) callback->onSuccess();
        } else {
            std::cout << "Service failed to start\n";
            if (callback) callback->onFailure();
        }
    }).detach();
}

void Service::sendMessage(const std::string& msg) {
    if (!started) {
        std::cerr << "[Error] Service not started\n";
        return;
    }
    std::cout << "Send message: " << msg << std::endl;
}

void Service::doSomethingElse() {
    if (!started) {
        std::cerr << "[Error] Service not started\n";
        return;
    }
    std::cout << "Do something else\n";
}

同步封装函数

#include "Service.h"
#include <future>
#include <iostream>
#include <exception>

enum class StartResult { Success, Failure };

StartResult startServiceAndWait(Service& svc) {
    std::promise<StartResult> p;
    std::future<StartResult> f = p.get_future();

    class MyCallback : public ServiceCallback {
        std::promise<StartResult>& promiseRef;
    public:
        MyCallback(std::promise<StartResult>& p) : promiseRef(p) {}
        void onSuccess() override { promiseRef.set_value(StartResult::Success); }
        void onFailure() override { promiseRef.set_value(StartResult::Failure); }
    };

    svc.start(new MyCallback(p));

    // 阻塞等待回调
    StartResult result = f.get(); // 成功或失败都会返回
    return result;
}

main.cpp

#include "Service.h"
#include <iostream>

int main() {
    Service svc;

    StartResult res = startServiceAndWait(svc);

    if (res == StartResult::Success) {
        std::cout << "Service ready, call interfaces\n";
        svc.sendMessage("Hello");
        svc.doSomethingElse();
    } else {
        std::cerr << "Service failed to start, handle error\n";
        // 可以选择退出或者重试
    }

    return 0;
}



网站公告

今日签到

点亮在社区的每一天
去签到