C++11 multi-threading basics

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.

Thanks in advance!
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?
Suppose the program was to count to 10. I want to output the number of times I called that thread to perform that operation (or to run that function).
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.
The program isn't going to execute and then stop running. The threads will be running simultaneously and note the number of calls to their functions.
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?
Last edited on
cppprogramming90 wrote:
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.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <atomic>
#include <future>
#include <vector>
#include <chrono>
#include <functional>

struct some_task
{
    int operator() ( int a ) const 
    {
        std::cout << "start task\n" << std::flush ;
        ++cnt ;
        
        // perform the task ...
        
        std::this_thread::sleep_for( std::chrono::seconds(1) ) ;
        
        return a*a ;
    }
    
    static std::atomic<int> cnt ;
};

std::atomic<int> some_task::cnt {0} ;

int main()
{
    int ss = 0 ;
    std::vector< std::future<int> > results ;
    
    // simple asynchronous execution of tasks
    for( int i = 0 ; i < 5 ; ++i )
    {
        // launch a task asynchronously
        results.emplace_back( std::async( std::launch::async, some_task(), i ) ) ;
    }
    std::cout << "**** launched five asynchronous tasks\n" << std::flush ;

    // asynchronous execution of tasks in designated threads
    std::vector< std::thread > threads ;
    for( int i = 5 ; i < 10 ; ++i )
    {
        std::packaged_task< int() >  task( std::bind( some_task(), i ) ) ; // create a task
        results.emplace_back( task.get_future() ) ; // store its future object
        threads.emplace_back( std::thread( std::move(task) ) ) ; // give it to a thread
    }
    std::cout << "**** launched five packaged tasks\n" << std::flush ;
    
    std::cout << "**** waiting for results...\n" << std::flush ;
    for( auto& t : threads ) t.join() ; // wai for threads to complete
    for( auto& f : results ) ss += f.get() ; // get the results
    
    // print out the number of times the task was executed
    std::cout << "**** done.\n**** function was called " << some_task::cnt << " times.\n"
              << "sum of results: "  << ss << '\n' ;
}
start task
start task
start task
**** launched five asynchronous tasks
start task
start task
start task
start task
start task
start task
**** launched five packaged tasks
**** waiting for results...
start task
**** done.
**** function was called 10 times.
sum of results: 285

http://coliru.stacked-crooked.com/a/9aaa8a9feb0956df
Last edited on
Topic archived. No new replies allowed.