我们提供了一个可以与其他API线程不安全的其他软件包接口(interface)的软件包。我们程序包的API完全基于消息,因此是异步的,从而为我们程序包的用户提供线程安全。因此,我们的程序包包装了一堆非线程安全的程序包,并提供了线程安全的API。这意味着我们包的用户可以从任何线程与我们包进行交互。

我们希望在保持线程安全的同时将同步API添加到我们的包中。我已经做过一些研究,并提出了两种可能的模式来做这件事,我将在下面分享。我对这两种方法都不完全满意,因此想知道社区是否对我们可以使用的模式有更多建议。请注意,以下代码仅用于设计和说明目的(c++伪代码),因此不打算编译。

方法1-程序包用户依赖项将数据访问类注入(inject)到我们的程序包中。我们使用运行时类型推断来访问这些类。

// Define an interface class for all data accessor classes
class DataAccessor
{

}

// Some random data
class FooData
{
    int foo;
    int bar;
}

// A concrete data accessor
class FooDataAccessor : public DataAccessor
{
public:
    FooData getFooData()
    {
        FooData fooDataCopy;
        {
            //Locks cachedFooData in this scope
            ScopedCriticalSection _(dataCriticalSection);
            fooDataCopy.foo = cachedFooData.foo;
            fooDataCopy.bar = cachedFooData.bar;
        }
        return fooDataCopy;
    }
    void setFooData(FooData& fooData)
    {
        //Locks cachedFooData in this scope
        ScopedCriticalSection _(dataCriticalSection);
        cachedFooData.foo = dooData.foo;
        cachedFooData.bar = dooData.bar;
    }

private:
    FooData cachedFooData;
    CriticalSection dataCriticalSection; //Use this for locking cachedFooData to set the data.
}

class OurPackage
{
    OurPackage(std::vector<DataAccessor*>); //constructor which is injected the data accessors so that our package customers can own their lifecycle.
}

// How package users would inject the data accessors into our package, then later access the data
int main()
{
    std::vector<DataAccessor*> dataAccessors;
    //The package customer now populates the data Accessors with the instances they need.
    dataAccessors.push_back(new FooDataAccessor());

    auto package = new OurPackage(dataAccessors);

    // How package users access the data, assume FooDataAccessor was at the front
    auto fooAccessor = dataAccessors.front();
    if (fooAccessor)
    {
        FooData data = fooAccessor->getFooData();
    }
}

// In OurPackage, set the actual data in caches
for (DataAccessor* dataAccessor : dataAccessors)
{
    //Use RTTI to find the instance we want
    if (auto dataAccessorTypeWeWant = dynamic_cast<DataAccessorTypeWeWant*>(dataAccessor) != nullptr)
    {
        //Set the data on dataAccessorTypeWeWant
        //For example, set FooData
        FooData fooData;
        fooData.foo = 1;
        fooData.bar = 2;
        dataAccessorTypeWeWant.setFooData(fooData);
        break;
    }
}

2-Use a singleton pattern instead

如果数据访问高速缓存是单例的,则包用户不必管理这些类的生命周期,也不必担心将指针指向其应用程序周围的数据访问高速缓存的实例。尽管这有单例的所有陷阱。

最佳答案

无论选择哪种模式,都应使用在<atomic>库中建立的Atomic Type,该类型自C++ 11起可用。如果您使用这种类型,则可以创建线程安全变量,例如:

// Some random data
class FooData
{
    std::atomic<int>  foo;
    std::atomic<int>  bar;
}

我从CPlusPlus分享了对该库的描述:

09-10 08:59
查看更多