Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

用C++API订阅流数据时出现异常

我用DolphinDB Database的C++ api订阅流数据,代码如下:

#include <iostream>
#include <string>
#include <ctime>
#include <fstream>
#include <sstream>
#include "Streaming.h"
using namespace dolphindb;
std::ofstream ofs("msg.log");
std::ostringstream oss;
std::string GetNowStr()
{
    auto now = std::time(nullptr);
    auto tm = *std::localtime(&now);
    char time[9];
    sprintf(time, "%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec);
    return time;
}

void OnMsg(Message msg) 
{
    if(msg->getString(0) != "600000")
        return;
    auto size = msg->size();
    //std::cout << size << std::endl;
    oss.str("");
    oss << GetNowStr() << " OnMsg: ";
    for(int i=0; i<size; i++) {
        oss << msg->getString(i) << ", ";
    }
    std::cout << oss.str() << std::endl;

    static int count=0; static std::time_t stamp=std::time(nullptr);
    if(++count % 1000 == 0) {
       ofs << oss.str() << std::endl;
       auto now = std::time(nullptr);
       ofs << "count: " << count << ", time: " << now << ", interval: " << now - stamp << std::endl;
       stamp = now;
       ofs.flush();
    }
  
}

int main(int argc, char* argv[])
{    
    std::string host, table, action;
    int client_listen_port, pub_port;
    host = "192.168.1.130";
    table = "trades";     
    action = "test";
    client_listen_port = 9000;
    pub_port = 8848;
    
    ThreadedClient client(client_listen_port);
    client.subscribe(host, pub_port, OnMsg, table, action, 0);
    while (true) {
        char c = getchar();
        if (c == 'q') {
            break;
        }
    }
    return 0;
}

调试时,发生异常,提示0x00007FFBB83D2400 (libDolphinDBAPI.dll)处(位于 c++apitesting.exe 中)引发的异常: 0xC0000005: 读取位置 0x0000000000000000 时发生访问冲突。如下面2图所示:subex.pngsubex2.png
请问可能是什么原因?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

client.subscribe返回值是一个智能指针ThreadSP,若不赋值给一个变量,会立即释放。

int main(int argc, char* argv[])
{    
    std::string host, table, action;
    int client_listen_port, pub_port;
    host = "192.168.1.130";
    table = "trades";     
    action = "test";
    client_listen_port = 9000;
    pub_port = 8848;
    
    ThreadedClient client(client_listen_port);
    auto t = client.subscribe(host, pub_port, OnMsg, table, action);
    while (true) {
        if (getchar() == 'q') {
            client.unsubscribe(host, pub_port, table, action);
            //t->join();
            break;
        }
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...