C++ 监视变量的更改值

标签 c++ object state tradestation

我正在将 TradeStation EasyLanguage 指标代码转换为 C++ DLL。使用 TradeStation API 可以像这样访问 C++ DLL 中的市场数据:

double currentBarDT = pELObject->DateTimeMD[iDataNumber]->AsDateTime[0];

我的问题是:

在 C++ 中是否有可能以某种方式“监视”或“监听”变量“currentBarDT”的值何时更改/更新?我想使用值的变化作为触发器来使用 Boost.Signals2 生成信号。

最佳答案

您可以使用适合您需要的条件变量。

http://en.cppreference.com/w/cpp/thread/condition_variable/notify_all

在您更新市场数据的信号中 (i)

在等待中,您将条件变量放在 i 上(例如,股票是否低于某个水平)

如果您需要更多信息,请告诉我,我可以详细说明并使其更明确。

#include <stdlib.h>     /* srand, rand */
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <atomic>
std::condition_variable cv;
std::mutex cv_m;
double StockPrice;//price of the stock
std::atomic<int> NbActiveThreads=0;//count the number of active alerts to the stock market

void waits(int ThreadID, int PriceLimit)
{
      std::unique_lock<std::mutex> lk(cv_m);
      cv.wait(lk, [PriceLimit]{return StockPrice >PriceLimit ;});
      std::cerr << "Thread "<< ThreadID << "...Selling stock.\n";
      --NbActiveThreads;
}

void signals()
{
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cerr << "GettingPrice "<<std::endl;
        std::unique_lock<std::mutex> lk(cv_m);
        /* generate secret number between 1 and 10: */
        StockPrice = rand() % 100 + 1;  
        std::cerr << "Price =" << StockPrice << std::endl;
        cv.notify_all();//updates the price and sell all the stocks if needed
        if (NbActiveThreads==0)
        {
            std::cerr <<"No more alerts "<<std::endl;
            return;
        }
    }

}

int main()
{
    NbActiveThreads=3;
    std::thread t1(waits,1,20), t2(waits,2,40), t3(waits,3,95), t4(signals);
    t1.join(); 
    t2.join(); 
    t3.join();
    t4.join();
    return 0;
}

希望对你有帮助

关于C++ 监视变量的更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16125713/

相关文章:

c++ - 最佳数据结构存储文本文件中的数字集

C++-为什么这里需要 'template'关键字?

c++ - 为什么双端队列使用的 RAM 比 C++ 中的 vector 多得多?

javascript更新对象数组中的所有值

database - 您应该将当前应用程序状态存储在数据库中吗?

javascript - 更新状态对象不会重新渲染动态创建的组件

c++ - 1>项目: error PRJ0003 : Error spawning 'rc.exe'

java - 从对象获取枚举的索引? ( java )

javascript - 如何按值删除javascript对象项?

reactjs - Redux - 错误 : Invalid value of type object for mergeProps