views:

48

answers:

1

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?

+1  A: 

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