Difference between “free-threaded” and “thread-safe”

前端 未结 2 1565

Sometimes I see the term \"free-threaded\" to describe a class or a method. It seems to have a similar or identical meaning to \"thread-safe\".

Is there a difference

2条回答
  •  隐瞒了意图╮
    2020-12-23 21:32

    I've just done some research on what "free-threaded" might mean, and I also ended up with COM. Let me first cite two passages from the 1998 edition of Don Box' book Essential COM. (The book actually contains more sections about the free-threaded model, but I'll leave it at that for now.)


    A thread executes in exactly one apartment at a time. Before a thread can use COM, it must first enter an apartment. […] COM defines two types of apartments: multithreaded apartments (MTAs) and singlethreaded apartments (STAs). Each process has at most one MTA; however, a process can contain multiple STAs. As their names imply, multiple threads can execute in an MTA concurrently, whereas only one thread can execute in an STA. […]

    — from pages 200-201. (Emphasis added by me.)


    Each CLSID in a DLL can have its own distinct ThreadingModel. […]

    • ThreadingModel="Both" indicates that the class can execute in either an MTA or an STA.
    • ThreadingModel="Free" indicates that the class can execute only in an MTA.
    • ThreadingModel="Apartment" indicates that the class can execute only in an STA.
    • The absence of a ThreadingModel value implies that the class can run only on the main STA. The main STA is defined as the first STA to be initialized in the process.

    — from page 204. (Formatting and emphasis added by me.)


    I take this to mean that a component (class) who is declared as free-threaded runs in an MTA, where concurrency of several threads is possible and calls to the component from different threads is explicitly allowed; ie. a free-threaded component supports a multithreaded environment. It would obviously have to be thread-safe in order to achieve this.

    The opposite would be a component that is designed for an STA, ie. only allows calls from one particular thread. Such a class would not have to be thread-safe (because COM will take care that no other thread than the one who "entered" / set up the STA can use the component in the first place, that is, COM protects the component from concurrent access).

    Conclusion: COM's term "free-threaded" essentially seems to have the same implications as the more general term "thread-safe".


    P.S.: This answer assumes that "thread-safe" basically means something like, "can deal with concurrent accesses (possibly by different threads)."

    P.P.S.: I do wonder whether "free-threaded" is the opposite of "having thread affinity".

提交回复
热议问题