0

Suppose I have thread A and thread B. Each thread owns a copy of the same object (let's call it "Foo" for simplicity). Certain pieces of data in Foo are initialized from a file on startup. So that means that on startup, I have to set the data read from the file in both copies of Foo. If no data is read from the file, then I still want to set the same data instance in both copies of Foo and not have each thread initialize the data separately.

Due to the architecture of the software I am working on, I am unable to perform this work on construction of either copy of Foo. So I am forced to do some type of Initialize() or similar method that is called after construction of the object. Since this all happens during the initialization phase of the application, I do not need to be concerned about thread-safety, but I am still concerned about the cleanliness of this solution. Here is what I have come up with so far:

ThreadA::Start()
{
    ...

    // Initialize() will read the data from the file if it exists. Otherwise, it will set default values.
    m_Foo.Initialize();

    // Now call Initialize() for thread B's copy of Foo while running in thread A but before thread B is even started. Pass in thread A's copy of Foo to set the values with. This should be safe to do since thread B has not even started yet.
    m_ThreadB.GetFoo().Initialize(m_Foo);

    ...
}

Is this the cleanest way to initialize the data in both copies of Foo? Thanks!

4

1 回答 1

0

我想你可能想多了,因为有线程。如果没有线程在运行,那么您可以使用任何您希望初始化它们的方法,因为没有竞争情况。甚至不要考虑线程。对于剩下的内容,我将改为调用 ThreadA 和 threadB BugbearA 和 BugbearB。

如果您只有两个 Bugbear,并且 BugbearA 总是在 BugbearB 之前启动,那么您的解决方案就是有史以来最好的解决方案。

如果情况实际上比你说的更复杂,我建议重构数据以拥有一个包含可能从文件初始化的数据的共享对象,以及每个 Bugbear 的非共享对象。Start() 的第一个 Bugbear 初始化共享对象。所有线程都将该数据复制到自己的 Foo 中并启动。

如果您以后需要,此重构还将为您设置多线程。您所要做的就是为共享对象提供适当的同步。

于 2013-09-01T04:44:52.133 回答