𝗧𝗵𝗲 𝗼𝗻𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝘀𝘁𝗱::𝘁𝗵𝗿𝗲𝗮𝗱 𝗮𝗻𝗱 𝘀𝘁𝗱::𝗷𝘁𝗵𝗿𝗲𝗮𝗱

Written by

in

Let’s consider a simple function called longTimeFunction. It simply prints a message indicating it has started, waits for three seconds, and then prints a message indicating it has finished.

If we run this function using std::jthread – leveraging the wrapper class’s dtor for convenience – the program will terminate successfully; this is because std::jthread automatically calls join() in its dtor when the thread object is destroyed.

If we use std::thread, however, the program will terminate with an error, as join() is not called automatically in the dtor, requiring us to call it manually.

This is a key difference between the two when terminating a thread by destroying the object. Of course, there are other differences as well.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *