簡體   English   中英

如果 object 在另一個線程中使用,是否可以使用對象的屬性?

[英]Can object’s property be used, if object used in another thread?

當主線程嘗試調用SetX時,下面的示例是否會產生未定義的行為並崩潰,因為雖然x屬性沒有在新線程中被訪問,但object本身是?

class Object{
public:
int x;
int y;

Object(int x, int y)
{
this->x = x;
this->y = y;
}

void SetX(int x)
{
this->x = x;
}

}*object = nullptr;

int *value_only = nullptr;

void ch()
{
    while(true) // assume there is some mechanism to quit loop
    {
         //with obj variable
         //readonly
         auto link = obj;
         auto y = obj->y;

         //write
         obj->y = 5;


         //without obj variable
         //read
         auto yy = *value_only;

         //write
         *value_only = 2;


         // note that obj->x is not touched
    }
}

int main()
{
obj = new Object(1,2);
value_only = &obj->y;

thread th(ch);

obj->SetX(4);

// assume, th termination is handled

return 0;
}

不,訪問同一個 object 的兩個不同成員沒有問題。

請注意,這兩個成員都是公共的,setter 除了設置成員之外什么都不做。 因此,您可以重寫ch以引用obj->y作為參數並且在 main 中,而不是調用SetX它可以使用int& x = obj->x; . 也許那么更明顯的是兩個線程實際上並不共享數據。

在線程中,您復制obj但僅復制指針。

但是,您的程序將由於未加入線程而崩潰。 std::thread在其析構函數中未加入(或分離)時調用std::terminate 無論如何,您都會泄漏obj的 memory 。 雖然從main返回時泄漏 memory 並不是什么大問題,但obj可能會管理需要在析構函數中正確關閉的其他資源(文件、數據庫連接等)。

我在代碼中的評論:

#include <future>
#include <mutex>

class Object
{
public:
    Object(int x, int y) :
        m_x{ x },
        m_y{ y }
    {
    }

    void SetX(int x)
    {
        m_x = x;
    }

    int GetX()
    {
        return m_x;
    }

private:
    int m_x;        
    int m_y;
};

int main()
{
    auto obj_ptr = std::make_shared<Object>(1, 2);

    // capture obj_ptr by value, making a copy of shared_ptr will increase its 
    // reference count. When the lambda finishes the shared_ptr will decrease the reference count.
    auto future = std::async([obj_ptr]
        {
            obj_ptr->SetX(3);
        });

    // destructor of the future will block until async is complete
    // so no race condition at shutdown
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM