简体   繁体   中英

Thread usage counter C++

In a C++ class, How can I limit the number calls/uses of a certain function for each thread? For example, each thread is allowed only to use a certain data setter for 3 times.

You just have to count how often the method has been called for each thread and then react accordingly:

void Foo::set(int x) {
    static std::map<std::thread::id,unsigned> counter;
    auto counts = ++counter[std::this_thread::get_id()];
    if (counts > max_counts) return;

    x_member = x;
}

This is just to outline the basic idea. I am not so sure about the static map. I am not even sure if it is a good idea to let the method itself implement the counter. I would rather put this elsewhere, eg each thread could get a CountedFoo instance that holds a reference to the actual Foo object and the CountedFoo controls the maximum number of calls.

PS: And of course, don't forget to use some synchronisation when multiple threads are calling the method concurrently (for the sake of brevity I did not include any mutex or similar in the above code).

Using std::map to store thread Ids as sugested by @formerlyknownas_463035818 would probably be the most robust solution, but synchronization might prove more complex.

The fastest solution to this issue is using thread_local . This will enable each thread to have its own copy of the counter. Here is the working example which might prove useful.

thread_local unsigned int N_Calls = 0;
std::mutex mtx;

void controlledIncreese(const std::string& thread_name){
    while (N_Calls < 3) {
        ++N_Calls;
        std::this_thread::sleep_for(std::chrono::seconds(rand() % 2));

        std::lock_guard<std::mutex> lock(mtx);      
        std::cout << "Call for thread " << thread_name.c_str() << ": " << N_Calls << '\n';
    }       
}

int main(){
    std::thread first_t(controlledIncreese, "first"), second_t(controlledIncreese, "second");
    first_t.join();
    second_t.join();
}

Since both Threads are using std::cout the actual output will be sequential, so this specific example is not very useful but it does provide easy working solution to thread execution counting problem.

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