multithread_fibonacci_call.cpp
Go to the documentation of this file.
2 
3 #include <sstream>
4 #include <iostream>
5 
6 #include <atomic>
7 #include <vector>
8 #include <thread>
9 #include <chrono>
10 
11 #include <ros/console.h>
12 
15 
16 typedef std::shared_ptr<std::atomic<bool>> FlagPtr;
17 
18 int argToInt(char* arg)
19 {
20  std::stringstream string_stream;
21  string_stream << arg;
22 
23  int value;
24  string_stream >> value;
25 
26 // ROS_INFO_STREAM("Converted " << arg << " to " << value);
27  return value;
28 }
29 
30 void callFibonacci(AtomicFibonacciPtr atomic_fibonacci, std::atomic<bool>& start_flag)
31 {
32  while (!start_flag.load())
33  {
34  std::chrono::duration<double> sleep_duration(0.001);
35  std::this_thread::sleep_for(sleep_duration);
36  }
37 
38  atomic_fibonacci->nextAndLog();
39 }
40 
41 int main(int argc, char **argv)
42 {
43  int last_number = 0;
44  int current_number = 1;
45  int max_number = 256;
46 
47  switch (argc)
48  {
49  case 1:
50  break;
51  case 2:
52  max_number = argToInt(argv[1]);
53  break;
54  case 3:
55  last_number = argToInt(argv[1]);
56  current_number = argToInt(argv[2]);
57  break;
58  case 4:
59  last_number = argToInt(argv[1]);
60  current_number = argToInt(argv[2]);
61  max_number = argToInt(argv[3]);
62  break;
63  default:
64  ROS_INFO_STREAM("Wrong number of arguments! Max. 3, got " << argc);
65  return 1;
66  }
67 
68  ROS_INFO("Initializing AtomicFibonacci with: ");
69  ROS_INFO_STREAM(" last_number = " << last_number);
70  ROS_INFO_STREAM(" current_number = " << current_number);
71  ROS_INFO_STREAM(" max_number = " << max_number);
72 
73  AtomicFibonacciPtr atomic_fibonacci = std::make_shared<AtomicFibonacci>(last_number,
74  current_number,
75  max_number);
76 
77  ROS_INFO_STREAM("Initialized AtomicFibonacci object");
78 
79  std::atomic<bool> start_flag;
80  start_flag = false;
81 
82  int number_of_threads = 20;
83  std::vector<std::thread> threads;
84 
85  ROS_INFO_STREAM("Start spawning " << number_of_threads << " threads");
86 
87  for (int i = 0; i < number_of_threads; ++i)
88  {
89  threads.push_back(std::thread(&callFibonacci, atomic_fibonacci, std::ref(start_flag)));
90  }
91 
92  ROS_INFO_STREAM("Spawning finished, let's go!");
93 
94  start_flag = true;
95 
96  for (int i = 0; i < threads.size(); ++i)
97  {
98  threads[i].join();
99  }
100 
101  ROS_INFO_STREAM("Finished. Goodbye!");
102 }
std::shared_ptr< AtomicFibonacci > AtomicFibonacciPtr
int main(int argc, char **argv)
int argToInt(char *arg)
std::shared_ptr< std::atomic< bool > > FlagPtr
#define ROS_INFO(...)
void callFibonacci(AtomicFibonacciPtr atomic_fibonacci, std::atomic< bool > &start_flag)
#define ROS_INFO_STREAM(args)


ros1_cpptemplate
Author(s): Alexander Reimann
autogenerated on Sat Sep 2 2017 02:37:58