Using commas and semicolons in C++ threads

143 Views Asked by At

I was reading on cppreference.com and encountered this bit of code:

int main()
{
    std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals);
    t1.join(); t2.join(), t3.join(), t4.join();
}

I was wondering if the last line was a typo.

Shouldn't it be this:

    int main()
    {
        std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals);
        t1.join(), t2.join(), t3.join(), t4.join();
    }

Or does it make no difference?

1

There are 1 best solutions below

1
On

It makes no difference. Both the comma operator and the semi-colon impose sequencing, the only difference is in how the results of each expression are handled. Since join has a void return type, even that tiny difference doesn't really matter. Either way, you'd join each thread, in order, from left to right.

Personally, I'd have used semicolons exclusively, because the comma operator (on the rare occasions it's used outside of a for loop increment step) implies the return values matter, but join being void return type makes that feature of the comma operator meaningless; t1.join(); t2.join(); t3.join(); t4.join(); would be equally correct, and remove any doubt about whether something fishy was going on with the comma operator.