简体   繁体   中英

About const and thread-safety of “pure” function objects

In my program, there are "functions" taking appropriate arguments, perform some computations, and return corresponding results. These "functions" have some internal states which are not externally visible; they are mainly memory buffers for temporary results. That means, those "functions" do not have any logical states.

Those memory buffers and other things are actually changing from each call to call, as the required buffer size may change depending on the input data.

Although those buffers are just for temporaries, I need to control their lifetime, constructing/destructing threads, etc.. And I don't want those temporaries to be supplied from the call site because their use is just internal to "functions". So I think those "functions" need to be implemented in terms of class (rather than function with/without static variables).

Since there is no externally visible state change (although there are states that are given and never change after the construction), I think it is better to qualify the function (I mean, the function call operator or whatever) with const . But then I'm not sure how should I deal with thread-safety of these temporary resources, because as well-known, in C++11, const by default implies thread-safety.

Currently the uses of functions are mainly single-threaded; there are only rare situations where instances of these functions are shared by several threads, so I externally locked the calls when really necessary. (More precisely, there is a lock guarding the whole series of computations. When another thread wants to perform a computation, it obtains that lock. There is currently no lock associated to each function.)

Implementations of the functions are separated from the outside, because I planned to use them in other projects.

Is it better to guard the computations with locks inside the implementations of functions? Or just leave the functions non-const although they are just (at least conceptually) pure functions? Or just mark them as const although they are not thread-safe (so are not really "const")? Or should I consider a different approach?

The easiest solution is to use a thread_local buffer.

int T::myfunction(int arg) const
{
    static thread_local U mybuffer;
    // impl...
}

thread_local will give you thread safety, as each thread will use its own buffer. Since it is static inside a function, the buffer will be retained after each function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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