C ++中的线程序列化是什么意思? [英] what does it mean by thread serialization in c++?

查看:125
本文介绍了C ++中的线程序列化是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解序列化对象以及如何将它们保存到磁盘,但是线程序列化实际上是什么意思?有人可以帮我这个忙,并指出正确的方向吗?

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 direction please?

推荐答案

您是对的,这是serialization的两种不同含义.您熟悉数据序列化,该序列化将数据结构转换为某些规范表示形式的字节流.在多线程中,序列化是指

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 <mutex>
std::mutex file_io_mutex;

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

这是资源获取即初始化(RAII)的示例,其中资源是同时获取和初始化的,并在超出范围时释放(执行到达大括号中).这是一个常见的习惯用法,即使代码在到达块末尾之前引发异常,也可以确保释放互斥体.

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.

这篇关于C ++中的线程序列化是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆