Thread exercise

Jan 31, 2022 at 4:38am
Ex: Write a program with two treads: one that writes hello every second and one that writes world! every second.

Is the following piece of code a right answer for the exercise above, please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <thread>

using namespace std::literals::chrono_literals;

void helloThread() {

    while (true) {
        std::cout << "First thread: hello\n";
        std::this_thread::sleep_for(1s);
    }
}

void worldThread() {

    while (true) {
        std::cout << "Second thread: world!\n";
        std::this_thread::sleep_for(1s);
    }
}

int main()
{
    std::thread hello(helloThread);
    std::thread world(worldThread);

    hello.join();
    world.join();

    system("pause");
    return 0;
}
Last edited on Jan 31, 2022 at 4:38am
Jan 31, 2022 at 5:21am
Yeah, seems about right.

But it's basically the same code in both, so perhaps the message itself could be a parameter.
https://www.cplusplus.com/reference/thread/thread/
Feb 1, 2022 at 5:17am
Yes, we could specify the message as a parameter to the functions. But one more important matter, won't data races occur? Both threads use same objects (std::cout, sleep_for()).
Last edited on Feb 1, 2022 at 5:18am
Feb 1, 2022 at 5:42am
https://en.cppreference.com/w/cpp/io/cout
Unless sync_with_stdio(false) has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted output.

Where 'safe' means you're not going to hose the machine by using it.

I'm not sure whether 'safe' would go as far as making sure every composite expression would always result in a whole line.
 
std::cout << position << " thread: " << message << "\n";

If the unit of interleaving is every <<, then you're in for a surprise at some point.
If you care about that, then build a string and output the result using a single <<.



For sleep_for, it's in this_thread
Feb 1, 2022 at 10:21am
Topic archived. No new replies allowed.