C++ Pi Calculator - Leibniz Formula(nearly) lock-free job queue of dynamic size (multiple read/write)Multithreading class for asynchronous usage of a custom client/server exchangeThe Term-inator: Pi editionImproved version of “Let's read a random Goodreads book…”Protected Pointer: a unique_ptr wrapper that auto encrypts and decrypts data in memoryMultithreaded Monte-Carlo IntegrationA new approach to multithreading in ExcelMinimalist dynamic task schedulerDouble loop for input handlingMultithreaded FRC Robot Framework (Kinda Big)

What is the tangent at a sharp point on a curve?

How do you say "Trust your struggle." in French?

Highest stage count that are used one right after the other?

Can you take a "free object interaction" while incapacitated?

What properties make a magic weapon befit a Rogue more than a DEX-based Fighter?

What (if any) is the reason to buy in small local stores?

Why didn’t Eve recognize the little cockroach as a living organism?

What do the positive and negative (+/-) transmit and receive pins mean on Ethernet cables?

How can an organ that provides biological immortality be unable to regenerate?

What 1968 Moog synthesizer was used in the Movie Apollo 11?

Why would five hundred and five same as one?

What should be the ideal length of sentences in a blog post for ease of reading?

What is this high flying aircraft over Pennsylvania?

is this saw blade faulty?

Are there any specific minhagim to celebrate Purim as a family?

Control width of columns in a tabular environment

Exposing a company lying about themselves in a tightly knit industry (videogames) : Is my career at risk on the long run?

Do native speakers use "ultima" and "proxima" frequently in spoken English?

"Marked down as someone wanting to sell shares." What does that mean?

Taking the numerator and the denominator

Output visual diagram of picture

Has the laser at Magurele, Romania reached the tenth of the Sun power?

Error in master's thesis, I do not know what to do

Why doesn't Gödel's incompleteness theorem apply to false statements?



C++ Pi Calculator - Leibniz Formula


(nearly) lock-free job queue of dynamic size (multiple read/write)Multithreading class for asynchronous usage of a custom client/server exchangeThe Term-inator: Pi editionImproved version of “Let's read a random Goodreads book…”Protected Pointer: a unique_ptr wrapper that auto encrypts and decrypts data in memoryMultithreaded Monte-Carlo IntegrationA new approach to multithreading in ExcelMinimalist dynamic task schedulerDouble loop for input handlingMultithreaded FRC Robot Framework (Kinda Big)













0












$begingroup$


Hi :) Yesterday I saw a CodeTrain video in where Daniel Shiffman tried to approximate Pi using the Leibniz series. It was interesting so I decided to try it too.



I wrote this console application with a simple goal: Approximate as fast as possible as many digits of Pi the program can until it reaches the maximum number the cicle counter can achieve(without starting to commit calculation errors with the series formula) OR the program is stopped.



It starts by first running two background threads which execute two functions that do all the job: piLoop(), for calculating the series; and displayLoop(), for refreshing the screen and displaying the actual calculated Pi. To prevent concurrency problems, mutexes are used to prevent the threads from accessing Pi and other program shared variables at the same time. The program runs until piCicles reaches the maximum value a long long int can get OR the End key is pressed.



The final program runs, by glancing at it(that means a very unreliable measurement), at an approximated rate of 30 million cicles per second in my computer. That means it can calculate the 10th digit of PI(around 87 billion cicles) in about an hour.



I want to know if there are some optimizations that can be made so the program can run at all his power.



Here's the code:



main.cpp



#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <windows.h>
#include <limits>

void piLoop();
void displayLoop();
void getShouldStop();

namespace
typedef std::numeric_limits<long double> ldbl;
typedef std::numeric_limits<long long int> ullint;

const char displayDigits = ldbl::max_digits10;
const short int updateDelay_ms = 50; // You can modify this value to change the speed of console refreshing.
const long long int maxCicles = ullint::max();

bool shouldStop = false;
long double PI = 0;
unsigned long long int piCicles = 0;
std::mutex piLock;


int main()

std::thread piCalculatorThread( piLoop );
std::thread displayUpdaterThread( displayLoop );
piCalculatorThread.join();
displayUpdaterThread.join();

std::cin.get();

return 0;


void getShouldStop()
shouldStop = GetAsyncKeyState( VK_END )

// If PI mutex is not locked, proceed to calculate the next PI, else wait
void piLoop()
while ( true )
piLock.lock();

if ( shouldStop )
piLock.unlock();
return;


// Here the series is calculated
PI += ((long double)((piCicles&1)>0 ? -1 : 1)) / (piCicles*2 + 1);

if ( piCicles == maxCicles )
shouldStop = true;
piLock.unlock();
return;


piCicles++;

piLock.unlock();



// Wait until PI mutex is unlocked, then refresh the screen.
void displayLoop()
std::cout.precision( displayDigits );
while ( true )
piLock.lock();

system("cls");
std::cout << "nn ----- PI Calculator ----- nn - "Seeing how PI is calculated is more enjoyable while eating some snacks."";
std::cout << "nnn PI: " << PI * 4;
std::cout << "n Cicles: " << piCicles << std::endl;
if ( maxCicles == piCicles ) // Just in case someone has the time to run this program for long enough
std::cout << "n Max precise 64-bit computable value reached!" << std::endl;

if ( !shouldStop ) getShouldStop();

piLock.unlock();

if ( shouldStop ) return;

std::this_thread::sleep_for( std::chrono::milliseconds( updateDelay_ms ) );




I think this code can also be run on other operating systems by removing the windows.h header and the getShouldStop() function as well, so Linux users may also give it a try :)



Here is a link to download the Windows executable if you want to test it.









share









$endgroup$
















    0












    $begingroup$


    Hi :) Yesterday I saw a CodeTrain video in where Daniel Shiffman tried to approximate Pi using the Leibniz series. It was interesting so I decided to try it too.



    I wrote this console application with a simple goal: Approximate as fast as possible as many digits of Pi the program can until it reaches the maximum number the cicle counter can achieve(without starting to commit calculation errors with the series formula) OR the program is stopped.



    It starts by first running two background threads which execute two functions that do all the job: piLoop(), for calculating the series; and displayLoop(), for refreshing the screen and displaying the actual calculated Pi. To prevent concurrency problems, mutexes are used to prevent the threads from accessing Pi and other program shared variables at the same time. The program runs until piCicles reaches the maximum value a long long int can get OR the End key is pressed.



    The final program runs, by glancing at it(that means a very unreliable measurement), at an approximated rate of 30 million cicles per second in my computer. That means it can calculate the 10th digit of PI(around 87 billion cicles) in about an hour.



    I want to know if there are some optimizations that can be made so the program can run at all his power.



    Here's the code:



    main.cpp



    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <chrono>
    #include <windows.h>
    #include <limits>

    void piLoop();
    void displayLoop();
    void getShouldStop();

    namespace
    typedef std::numeric_limits<long double> ldbl;
    typedef std::numeric_limits<long long int> ullint;

    const char displayDigits = ldbl::max_digits10;
    const short int updateDelay_ms = 50; // You can modify this value to change the speed of console refreshing.
    const long long int maxCicles = ullint::max();

    bool shouldStop = false;
    long double PI = 0;
    unsigned long long int piCicles = 0;
    std::mutex piLock;


    int main()

    std::thread piCalculatorThread( piLoop );
    std::thread displayUpdaterThread( displayLoop );
    piCalculatorThread.join();
    displayUpdaterThread.join();

    std::cin.get();

    return 0;


    void getShouldStop()
    shouldStop = GetAsyncKeyState( VK_END )

    // If PI mutex is not locked, proceed to calculate the next PI, else wait
    void piLoop()
    while ( true )
    piLock.lock();

    if ( shouldStop )
    piLock.unlock();
    return;


    // Here the series is calculated
    PI += ((long double)((piCicles&1)>0 ? -1 : 1)) / (piCicles*2 + 1);

    if ( piCicles == maxCicles )
    shouldStop = true;
    piLock.unlock();
    return;


    piCicles++;

    piLock.unlock();



    // Wait until PI mutex is unlocked, then refresh the screen.
    void displayLoop()
    std::cout.precision( displayDigits );
    while ( true )
    piLock.lock();

    system("cls");
    std::cout << "nn ----- PI Calculator ----- nn - "Seeing how PI is calculated is more enjoyable while eating some snacks."";
    std::cout << "nnn PI: " << PI * 4;
    std::cout << "n Cicles: " << piCicles << std::endl;
    if ( maxCicles == piCicles ) // Just in case someone has the time to run this program for long enough
    std::cout << "n Max precise 64-bit computable value reached!" << std::endl;

    if ( !shouldStop ) getShouldStop();

    piLock.unlock();

    if ( shouldStop ) return;

    std::this_thread::sleep_for( std::chrono::milliseconds( updateDelay_ms ) );




    I think this code can also be run on other operating systems by removing the windows.h header and the getShouldStop() function as well, so Linux users may also give it a try :)



    Here is a link to download the Windows executable if you want to test it.









    share









    $endgroup$














      0












      0








      0





      $begingroup$


      Hi :) Yesterday I saw a CodeTrain video in where Daniel Shiffman tried to approximate Pi using the Leibniz series. It was interesting so I decided to try it too.



      I wrote this console application with a simple goal: Approximate as fast as possible as many digits of Pi the program can until it reaches the maximum number the cicle counter can achieve(without starting to commit calculation errors with the series formula) OR the program is stopped.



      It starts by first running two background threads which execute two functions that do all the job: piLoop(), for calculating the series; and displayLoop(), for refreshing the screen and displaying the actual calculated Pi. To prevent concurrency problems, mutexes are used to prevent the threads from accessing Pi and other program shared variables at the same time. The program runs until piCicles reaches the maximum value a long long int can get OR the End key is pressed.



      The final program runs, by glancing at it(that means a very unreliable measurement), at an approximated rate of 30 million cicles per second in my computer. That means it can calculate the 10th digit of PI(around 87 billion cicles) in about an hour.



      I want to know if there are some optimizations that can be made so the program can run at all his power.



      Here's the code:



      main.cpp



      #include <iostream>
      #include <thread>
      #include <mutex>
      #include <chrono>
      #include <windows.h>
      #include <limits>

      void piLoop();
      void displayLoop();
      void getShouldStop();

      namespace
      typedef std::numeric_limits<long double> ldbl;
      typedef std::numeric_limits<long long int> ullint;

      const char displayDigits = ldbl::max_digits10;
      const short int updateDelay_ms = 50; // You can modify this value to change the speed of console refreshing.
      const long long int maxCicles = ullint::max();

      bool shouldStop = false;
      long double PI = 0;
      unsigned long long int piCicles = 0;
      std::mutex piLock;


      int main()

      std::thread piCalculatorThread( piLoop );
      std::thread displayUpdaterThread( displayLoop );
      piCalculatorThread.join();
      displayUpdaterThread.join();

      std::cin.get();

      return 0;


      void getShouldStop()
      shouldStop = GetAsyncKeyState( VK_END )

      // If PI mutex is not locked, proceed to calculate the next PI, else wait
      void piLoop()
      while ( true )
      piLock.lock();

      if ( shouldStop )
      piLock.unlock();
      return;


      // Here the series is calculated
      PI += ((long double)((piCicles&1)>0 ? -1 : 1)) / (piCicles*2 + 1);

      if ( piCicles == maxCicles )
      shouldStop = true;
      piLock.unlock();
      return;


      piCicles++;

      piLock.unlock();



      // Wait until PI mutex is unlocked, then refresh the screen.
      void displayLoop()
      std::cout.precision( displayDigits );
      while ( true )
      piLock.lock();

      system("cls");
      std::cout << "nn ----- PI Calculator ----- nn - "Seeing how PI is calculated is more enjoyable while eating some snacks."";
      std::cout << "nnn PI: " << PI * 4;
      std::cout << "n Cicles: " << piCicles << std::endl;
      if ( maxCicles == piCicles ) // Just in case someone has the time to run this program for long enough
      std::cout << "n Max precise 64-bit computable value reached!" << std::endl;

      if ( !shouldStop ) getShouldStop();

      piLock.unlock();

      if ( shouldStop ) return;

      std::this_thread::sleep_for( std::chrono::milliseconds( updateDelay_ms ) );




      I think this code can also be run on other operating systems by removing the windows.h header and the getShouldStop() function as well, so Linux users may also give it a try :)



      Here is a link to download the Windows executable if you want to test it.









      share









      $endgroup$




      Hi :) Yesterday I saw a CodeTrain video in where Daniel Shiffman tried to approximate Pi using the Leibniz series. It was interesting so I decided to try it too.



      I wrote this console application with a simple goal: Approximate as fast as possible as many digits of Pi the program can until it reaches the maximum number the cicle counter can achieve(without starting to commit calculation errors with the series formula) OR the program is stopped.



      It starts by first running two background threads which execute two functions that do all the job: piLoop(), for calculating the series; and displayLoop(), for refreshing the screen and displaying the actual calculated Pi. To prevent concurrency problems, mutexes are used to prevent the threads from accessing Pi and other program shared variables at the same time. The program runs until piCicles reaches the maximum value a long long int can get OR the End key is pressed.



      The final program runs, by glancing at it(that means a very unreliable measurement), at an approximated rate of 30 million cicles per second in my computer. That means it can calculate the 10th digit of PI(around 87 billion cicles) in about an hour.



      I want to know if there are some optimizations that can be made so the program can run at all his power.



      Here's the code:



      main.cpp



      #include <iostream>
      #include <thread>
      #include <mutex>
      #include <chrono>
      #include <windows.h>
      #include <limits>

      void piLoop();
      void displayLoop();
      void getShouldStop();

      namespace
      typedef std::numeric_limits<long double> ldbl;
      typedef std::numeric_limits<long long int> ullint;

      const char displayDigits = ldbl::max_digits10;
      const short int updateDelay_ms = 50; // You can modify this value to change the speed of console refreshing.
      const long long int maxCicles = ullint::max();

      bool shouldStop = false;
      long double PI = 0;
      unsigned long long int piCicles = 0;
      std::mutex piLock;


      int main()

      std::thread piCalculatorThread( piLoop );
      std::thread displayUpdaterThread( displayLoop );
      piCalculatorThread.join();
      displayUpdaterThread.join();

      std::cin.get();

      return 0;


      void getShouldStop()
      shouldStop = GetAsyncKeyState( VK_END )

      // If PI mutex is not locked, proceed to calculate the next PI, else wait
      void piLoop()
      while ( true )
      piLock.lock();

      if ( shouldStop )
      piLock.unlock();
      return;


      // Here the series is calculated
      PI += ((long double)((piCicles&1)>0 ? -1 : 1)) / (piCicles*2 + 1);

      if ( piCicles == maxCicles )
      shouldStop = true;
      piLock.unlock();
      return;


      piCicles++;

      piLock.unlock();



      // Wait until PI mutex is unlocked, then refresh the screen.
      void displayLoop()
      std::cout.precision( displayDigits );
      while ( true )
      piLock.lock();

      system("cls");
      std::cout << "nn ----- PI Calculator ----- nn - "Seeing how PI is calculated is more enjoyable while eating some snacks."";
      std::cout << "nnn PI: " << PI * 4;
      std::cout << "n Cicles: " << piCicles << std::endl;
      if ( maxCicles == piCicles ) // Just in case someone has the time to run this program for long enough
      std::cout << "n Max precise 64-bit computable value reached!" << std::endl;

      if ( !shouldStop ) getShouldStop();

      piLock.unlock();

      if ( shouldStop ) return;

      std::this_thread::sleep_for( std::chrono::milliseconds( updateDelay_ms ) );




      I think this code can also be run on other operating systems by removing the windows.h header and the getShouldStop() function as well, so Linux users may also give it a try :)



      Here is a link to download the Windows executable if you want to test it.







      c++ performance multithreading windows numerical-methods





      share












      share










      share



      share










      asked 9 mins ago









      Nikko77Nikko77

      234




      234




















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215796%2fc-pi-calculator-leibniz-formula%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215796%2fc-pi-calculator-leibniz-formula%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订