quantdev
quantdev

Reputation: 23813

C++ : How to count the number of threads used to call a function?

I would like to know how many different threads used an object function during its lifetime.

My naive approach was to create a base class to register the id of calling threads :

class threaded_object
{
public:
    virtual ~threaded_object() {}

protected:
    void register_call()
    {
                    // error ! if the ID is reused, the new thread wont be accounted for.
        callers_ids.insert(std::this_thread::get_id());
    }

    size_t get_threads_cout() const
    {
        return callers_ids.size();
    }

private:
    std::set<std::thread::id> callers_ids;
};

And to inherits it in my client classes, here I will count how many threads used foo()

class MyObject : public threaded_object
{
 void foo()
 {
    register_call();
    // ...
 }
};

But it doesn't work in the general case, the standards says in section § 30.3.1.1

The library may reuse the value of a thread::id of a terminated thread that can no longer be joined

Question:

Is there a portable and safe way to do this ?

Upvotes: 2

Views: 2840

Answers (1)

Slava
Slava

Reputation: 44268

I believe you can use thread-local storage to count how many threads called your function:

namespace {
    thread_local bool used = false;
}


void register_call()
{
    if( !used ) {
        used = true;
        ++count;
    }
}

Of course this code is to show the idea, in real code it can be a pointer to container, that holds addresses of functions which are in interest etc.

Upvotes: 1

Related Questions