#include #include #include #include #include using namespace std; const int THREAD_COUNT{1}; const int COUNT_LIMIT{200'000'000}; const int KILL_LOOP{1000}; struct ThreadInfoT { double * address; int id; int nThread; }; static void * ThreadFunction (void * arg) { ThreadInfoT * tInfo; tInfo = reinterpret_cast(arg); int i; float signTerm = 1; for(int j =0; j < KILL_LOOP; ++j) { (tInfo->address)[tInfo->id-1] = 0; for(i = tInfo->id * 2 + 1; i < COUNT_LIMIT; i += 2*tInfo->nThread) { if (i%4 ==1) { signTerm = 1; } else { signTerm = -1; } (tInfo->address)[tInfo->id-1] += signTerm *4.0/static_cast(i); } } return nullptr; } int main() { vector tInfos(THREAD_COUNT); vector threads(THREAD_COUNT); double * storage = new double [THREAD_COUNT]; int info; for(int i = 0; i < THREAD_COUNT; ++i) { ThreadInfoT * tInfo = new ThreadInfoT; tInfo->id = i+1; tInfo->address = storage; tInfo->nThread = THREAD_COUNT; tInfos[i] = tInfo; info = pthread_create(&(threads[i]) , nullptr, ThreadFunction, tInfo); if (info != 0) { perror("pthread_create: "); } } void * res; for( int i = 0; i < THREAD_COUNT; ++i) { pthread_join(threads[i], & res); delete tInfos[i]; } double pi{4}; for (int i = 0; i < THREAD_COUNT; ++i) { pi += storage[i]; } cout << setprecision(10); cout << "Pi is approximately " << pi << endl; delete[] storage; return 0; }