3

I am playing around with Cilk and I am having an issue with printing synchronously. Printing is slow, so it's hard to keep the prints synchronous. For example...

void ftn(int x)
{
    if (x % 2 == 0)
    {
        std::cout << "printing.. " << x << std::endl;
    }
    else
    {
        cilk_spawn ftn(x/2);
        cilk_spawn ftn(x++);
        cilk_spawn ftn(x*x);

        cilk_sync;
    }

}

For the most part, printing is ok. However, it occasionally goes out of sync and a second print statement from another thread will start in the middle of one thread's print statement.

How do you make C/Cilk printing threadsafe? How can I ensure that these stay synchronous?

cilk
  • 231
  • 1
  • 2
  • 5

2 Answers2

1

In order to solve your problem, you need to serialize writing to the output stream. For that purpose, Cilk Plus provides high-level primitives called "reducers". Specifically, you need to use the reducer_ostream:

cilk::reducer<cilk::op_ostream> hyper_cout(std::cout);
*hyper_cout << "Reducer cout:  ";

A complete example is available on the Cilk Plus website.

1

You need some form of mutual exclusion construct (such as a lock) to prevent several threads from mixing up their output - acquire a lock before the call to cout and release it afterwards. I'm not familiar with Cilk but it should have constructs to do this.

Since you said you're just playing around, this should work fine, but otherwise, locks are expensive and should generally be avoided. In real-word applications though, individual threads usually don't "print" anything - they mostly perform computations on independent sets of data - and hence the problem you described doesn't arise.

casablanca
  • 69,683
  • 7
  • 133
  • 150