#include #include #include // needs to link with -lpthread using namespace std; const size_t WORKER_COUNT {10}; const size_t WORK_SIZE {1'000'000'000}; struct WorkT { size_t first; size_t last; size_t index; }; void * PiWorker(void * workp); // yuck. long double pi[WORKER_COUNT]; int main() { pthread_t workers[WORKER_COUNT]; for(size_t i =0; i < WORKER_COUNT; ++i) { pthread_t tid; pthread_create(&tid, nullptr, PiWorker, // Y U C K reinterpret_cast ( new WorkT{i*WORK_SIZE, (i+1)*WORK_SIZE, i})); workers[i] = tid; } long double finalPi{0}; for(size_t i = 0; i < WORKER_COUNT; ++i) { cout << "Waiting for " << workers[i] << endl; pthread_join(workers[i],nullptr); finalPi += pi[i]; } cout << "PI = " << setprecision(20) << finalPi << endl; return 0; } void * PiWorker(void * workp){ WorkT & work = * reinterpret_cast(workp); cout << pthread_self() << " working on " << work.first << " to " << work.last << endl; int sign{-1}; long double term = work.first * 2 + 1; if (work.first %2 == 0) { sign = 1; } for(size_t i = work.first; i < work.last; ++i) { pi[work.index] += sign * 4.0/term; term += 2; sign *= -1; } delete reinterpret_cast (workp); pthread_exit(0); }