简体   繁体   English

实现Sync特性是否会更改编译器输出?

[英]Does implementing the Sync trait change the compiler output?

If I mark my struct as Sync will the compiler output differ? 如果我将结构标记为Sync则编译器输出会有所不同吗? Will the compiler implement some Mutex -like magic? 编译器会实现Mutex的魔术吗?

struct MyStruct {
    data: RefCell<u32>,
}
unsafe impl Sync for MyStruct {}
unsafe impl Send for MyStruct {}

The compiler uses a mechanism named "language items" to reference items (types, traits, etc.) that are defined in a library (usually core ) but are used by the compiler, whether that be in code generated by the compiler, for validating the code or for producing specialized error messages. 编译器使用一种名为“语言项”的机制来引用在库(通常为core )中定义但由编译器使用的项(类型,特征等),以验证它们是否在编译器生成的代码中使用代码或用于生成专门的错误消息。

Send and Sync are defined in the core library. SendSynccore库中定义。 Sync is a language item, but Send isn't. Sync是一种语言的项目,但Send并非如此。 The only reference to Sync I could find in the compiler is where it checks that the type of a static variable implements Sync . 我在编译器中只能找到Sync引用,它是在其中检查static变量的类型是否实现Sync ( Send and Sync used to be more special to the compiler. Before auto traits were added to the language, they were implemented as "auto traits" explicitly.) SendSync以前对于编译器更特殊。在将自动特征添加到语言之前,它们已明确实现为“自动特征”。)

Other than that, the compiler doesn't care about what Send and Sync mean. 除此之外,编译器不在乎SendSync含义。 It's the libraries (specifically, types/functions that are generic over Send / Sync types) that give the traits their meaning. 赋予特征的含义的是库(特别是,类型/功能在“ Send / Sync类型上通用)。

Neither trait influences what code is emitted by the compiler regarding a particular type. 两种特性都不会影响编译器针对特定类型发出的代码。 Making a type "thread-safe" is not something that can be done automatically. 将类型设为“线程安全”不是可以自动完成的事情。 Consider a struct with many fields: even if the fields are all atomic types, a partially updated struct might not be in a valid state. 考虑具有许多字段的结构:即使这些字段都是原子类型,部分更新的结构也可能不会处于有效状态。 The compiler doesn't know about the invariants of a particular type; 编译器不知道特定类型的不变量。 only the programmer knows them. 只有程序员才知道。 Therefore, it's the programmer's responsibility to make the type thread-safe. 因此,使类型成为线程安全是程序员的责任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM