1

I'm trying to run the code for fibonacci series algorithm in parallel.The problem is that my function returns a string and is recursive. I've tried using future and promise,it doesn't seem to work though. Can anyone point out where I'm going wrong?

void fib(int n,promise<string> *x)

    string bit;
    if (n == 0)
    {
         x->set_value("0");
    }
    else if (n == 1) {
        x->set_value("1");
    }
    else if (n > 1) {
        promise <string> p1;
        promise <string> p2;
        thread *t = new thread[2];
        t[0] = thread(fib, n-1,&p1);
        t[0] = thread(fib, n - 2,&p2);
        t[0].join();
        t[1].join();
        future<string> ret = p1.get_future();
        future<string> re = p2.get_future();
        string a = ret.get();
        string b = re.get();
        x->set_value( a + b);
    }

}
walnut
  • 21,629
  • 4
  • 23
  • 59
Shahzaib
  • 103
  • 1
  • 11
  • 3
    Cool exercise, but on a side note, you probably won't get any speedup, as the overhead of launching all those threads is much higher than the overhead of just calling a function. – parktomatomi Dec 17 '19 at 05:48
  • 2
    t[0] = thread(fib, n-1,&p1); t[0] = thread(fib, n - 2,&p2); I think, both r assigned at same index and join should be called at the end of program , not in between. – Build Succeeded Dec 17 '19 at 05:54
  • 1
    "*,it doesn't seem to work though*": Please describe what exactly the problem with your current code is. Are there error messages, does it not produce the correct output, etc. See [ask]. – walnut Dec 17 '19 at 05:55
  • 1
    Help for searching and understanding: A std::promise permits: to set a value, a notification or an exception. That result can in addition delayed be provided by the promise. A std::future permits to pick up the value from the promise. asks the promise, if the value is available. wait for the notification of the promise. That waiting can be done with a relative time duration or an absolute time point. => Replacement for condition variables. create a shared future (std::shared_future). Below link for details: https://www.modernescpp.com/index.php/promise-and-future – Build Succeeded Dec 17 '19 at 06:07
  • @walnut what i mean is that I'm not getting better performance with threads. What i want is to reduce the execution time for large inputs l. Like calculating the fibobacci series for n=50 or 100. – Shahzaib Dec 17 '19 at 18:33
  • @Jak You are not going to get better performance with threads for this as explained by the first comment. The correct thing to do to make the algorithm faster is not to recurse on both `fib(n-1)` and `fib(n-2)`, see e.g. https://stackoverflow.com/questions/3337455/how-to-generate-fibonacci-faster – walnut Dec 17 '19 at 19:41

0 Answers0