QuantLib多线程/并发

时间:2013-05-17 15:29:44

标签: c++ multithreading concurrency quantlib

我对QuantLib相当新,并且还不知道源代码的所有细节,但我试图测试几个选项的NPV的简单多线程计算并且我得到运行时错误。这是我的测试代码,它刚刚从QL中包含的EquityOpiton示例扩展而来。

// options
VanillaOption europeanOption(payoff, europeanExercise);
VanillaOption bermudanOption(payoff, bermudanExercise);
VanillaOption americanOption(payoff, americanExercise);

boost::thread_group worker_threads;
for( int x = 0; x < 3; ++x )
{
     switch (x)
     {
     case 0:
        europeanOption.setPricingEngine(boost::shared_ptr(
           new FDEuropeanEngine(bsmProcess,
                                                100,99)));
        worker_threads.create_thread( boost::bind( &VanillaOption::NPV, &europeanOption ) );
     case 1:
        bermudanOption.setPricingEngine(boost::shared_ptr(
          new FDBermudanEngine(bsmProcess,
                                                100,99)));
        worker_threads.create_thread( boost::bind( &VanillaOption::NPV, &bermudanOption ) );
     case 2:
       americanOption.setPricingEngine(boost::shared_ptr(
         new FDAmericanEngine(bsmProcess,
                                                100,99)));
        worker_threads.create_thread( boost::bind( &VanillaOption::NPV, &americanOption ) );
      default:
        break;
  }
}


worker_threads.join_all();

究竟是什么原因导致这些运行时错误以及如何解决?我猜它与共享指针有关,但它们在整个QL中被大量使用我注意到了,我不确定是哪一个引起了这个问题。

1 个答案:

答案 0 :(得分:2)

似乎你忘了在每个案例后加上休息。试试以下

 switch (x)
 {
 case 0:
 {
    europeanOption.setPricingEngine(boost::shared_ptr(
       new FDEuropeanEngine(bsmProcess, 100,99)));
    worker_threads.create_thread( boost::bind( &VanillaOption::NPV, &europeanOption )  );
    break;
 }
 case 1:
 {
    opt = &bermudanOption;
    bermudanOption.setPricingEngine(boost::shared_ptr(
      new FDBermudanEngine(bsmProcess,
                                            100,99)));
    worker_threads.create_thread( boost::bind( &VanillaOption::NPV, &bermudanOption ) );
    break;
 }
 case 2:
 {
   americanOption.setPricingEngine(boost::shared_ptr(
     new FDAmericanEngine(bsmProcess,
                                            100,99)));
    worker_threads.create_thread( boost::bind( &VanillaOption::NPV, &americanOption ) );
    break;
  }
  default:
    break;
 }