I have a C# project in which I need to determine if a given date is a holiday in a given country. I can use the date and calendar functionality in QuantLib for this purpose. QuantLib is written in C++, so I have written a wrapper to call this code. I would like to know if the code I'm using is thread-safe.

Here are the QuantLib calls I use in C++ to determine if a given date is a holiday:

extern "C" _declspec(dllexport) int isHoliday(int year, int month, int day,
    int trueValue, int falseValue, int errorValue)
{
    try
    {
        QuantLib::Calendar cal = QuantLib::UnitedStates();
        QuantLib::Date date(day, (QuantLib::Month)month, year);

        return cal.isHoliday(date) ? trueValue : falseValue;
    }
    catch(...)
    {
        return errorValue;
    }
}

Here is the C# signature I use to call my C++ code:

[DllImport("QuantLibHelpers.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int isHoliday(int year, int month, int day,
    int trueValue, int falseValue, int errorValue);

The most I could find about the QuantLib code is here. Nothing in there looks thread-unsafe, but I can't be sure. More generally, regardless of my use of QuantLib, is calling C++ code like this thread-safe? Is it possible that one thread, while creating the date object, gets interrupted by another thread which somehow corrupts the first date object? I know that I can lock all calls to the C# isHoliday() static function if this code is indeed thread-unsafe.

Note that my code works fine as is.


I know about QLNet which is a .Net port of QuantLib. I prefer to use QuantLib because it appears to have better support.

有帮助吗?

解决方案

There are lots of things in QuantLib which are not thread-safe (which goes to show that Sean's answer is correct: always check!) but this particular one is safe, except for one thing: the very first construction of a UnitedStates instance will initialize a static variable in the constructor, so you might want to take care of that case. Once the first instance is built, it's safe to build others in parallel threads.

The construction of a Date instance and the call to isHoliday are both safe.

其他提示

It's all depends on the implementation of the C++ library.

It's no different to if you're consuming a C# assembly. When you call a method on an object how do you know if it's thread safe? The answer is you don't, you have to check the library documentation.

If you're not sure then you could always add a thread-safe wrapper in your own code in order to serialize calls to API.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top