what does it mean by thread serialization in c++?

前端 未结 3 1773
后悔当初
后悔当初 2021-02-20 01:13

I know about serializing objects and how they are saved to disk, but what does thread serialization actually mean? Could any one help me on this one and point me in the right di

3条回答
  •  名媛妹妹
    2021-02-20 02:17

    You are right that these are two different meanings of serialization. You are familiar with data serialization which is to convert a data structure into a stream of bytes in some canonical representation. In multi-threading the term serialization means mutual exclusion for thread or process synchronization which means only one thread may operate on a data structure at a time. C++11 provides for serialization between threads using a std::mutex

    #include 
    std::mutex file_io_mutex;
    
    {
        std::lock_guard guard(file_io_mutex);
        std::out << "Only one thread at a time will execute this line." << std::endl;
    }
    

    This is an example of Resource Acquisition Is Initialization (RAII) where the resource is acquired and initialized at the same time, and released when it goes out of scope (execution reaches the close curly bracket). This is a common idiom, it ensures that the mutex is released even if the code throws an exception before reaching the end of the block.

提交回复
热议问题