#include #include #include #include #include #include using namespace std; void PiWorker(unsigned long start, unsigned long stop, long double & work); int main(int argc, char * argv[]) { long double threads{10}; unsigned long workSize{1'000}; int opt; while((opt = getopt(argc, argv, "l:w:")) != -1) { switch(opt) { case 'l': workSize = max(atoi(optarg), 100); break; case 'w': threads = max(atoi(optarg), 1); break; default: cout << argv[0] << "-l work size -w threads " << endl; } } vector pi(threads,0.0); // vector workers; vector workers(threads); long double finalPi{0}; for(size_t i = 0; i < threads; ++i) { //workers.emplace_back(PiWorker, i*workSize, (i+1)*workSize, ref(pi[i])); workers[i] = jthread{PiWorker, i*workSize, (i+1)*workSize, ref(pi[i])}; } for(size_t i = 0; i < workers.size(); ++i) { workers[i].join(); finalPi += pi[i]; } cout << "PI = " << setprecision(20) << finalPi << endl; return 0; } void PiWorker(unsigned long first, unsigned long last, long double & work){ cout << this_thread::get_id() << " is working on " << first << " to " << last << endl; work = 0; int sign{-1}; long double term = first * 2 + 1; if (first %2 == 0) { sign = 1; } for(unsigned long i = first; i < last; ++i) { work += sign * 4.0/term; term += 2; sign *= -1; } }