I am trying to better understand how to implement threads in C++.
Suppose for instance I wanted to create 2 threads that do [insert anything] and I wanted to specify how many calls were made to that particular thread:
Sample output being: "Thread 1 (or 2) was called X times"
How would this be done?
I know I can use "std::this_thread::get_id" to get the thread IDs, but I wasn't sure how to keep track of calls.
What do you mean by "calls to a thread"? When you start a new thread, you tell it to run a particular function. Are you meaning some kind of "call" to it while it is running?
You create a robot to perform a task, then it self-destructs. You do this many times. One day you ask the robot "How many times have I created you?", does that make any sense at all? You should know.
So you are creating them only once, and they continuously run for the duration of the program, and you want to profile each thread separately? I guess you get a profiler that can do this, or you could use a logging library.
Or are you talking about having one thread ask another thread to do a specific task after it has already been created?
The program isn't going to execute and then stop running.
But the thread is. That's the point.
You don't "call" a thread... It works like this:
1) You create a thread
2) When you create it, you give it a single function to run. This is like that thread's "main"
3) The thread runs that function
4) When that function returns... the thread is destroyed. (Just like how when main() is done.. your program closes).
If you want a thread to keep doing stuff... you can't let that function exit. You have to keep looping. And if all you want to do is count how many times it's looped...
1 2 3 4 5 6 7 8 9 10 11 12 13
// note: this sample is simplistic and does not use any mutexes!!!!!
// remember that any memory/variables shared between threads must
// be guarded or *very bad things* will happen.
void myThreadEntry()
{
int numTimesRun = 0;
while( keep_this_thread_open )
{
doSomething();
numTimesRun++; // count how many times doSomething is done
}
}
> I want to output the number of times I called that thread to perform that operation (or to run that function).
> The threads will be running simultaneously and note the number of calls to their functions.
To execute a function asynchronously, std::async( std::launch::async, function_to_be_executed, arguments_to_be_passed... ) ;
To execute a function asynchronously in a designated thread, create a std::packaged_task<> and then hand over the the task to a thread. (If there are no results to be returned, we can hand over the function directly.)