Thread: Thread exercise

  1. #1
    Registered User
    Join Date
    Sep 2020
    Posts
    150

    Thread exercise

    I just solved this exercise from https://www.stroustrup.com/4thExercises.pdf Page 3

    /*
    Write a program with two treads: one that writes hello every second and one that writes world! every second
    */
    Code:
    #include <iostream>
    #include <thread>
    #include <chrono>
    
    
    void print(const char* msg)
    {
      while (true)
      {
        std::cout << msg;
        std::this_thread::sleep_for(std::chrono::seconds(1));
      }
    };
    
    
    int main()
    {
      std::thread t1(print, "Hello ");
      std::thread t2(print, "world!");
      t1.join();
      t2.join();
    }
    Does anyone see a better solution ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Looks pretty good to me.

    The ; at the end of line 13 is redundant.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    Thanks Salem,

    not sure where the ; came from.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help exercise thread posix , C
    By Keplero90 in forum C Programming
    Replies: 7
    Last Post: 06-18-2020, 05:06 AM
  2. Replies: 3
    Last Post: 11-20-2011, 12:01 AM
  3. Replies: 2
    Last Post: 07-01-2007, 07:11 AM
  4. pointer to main thread from worker thread?
    By draegon in forum C++ Programming
    Replies: 2
    Last Post: 10-27-2005, 06:35 AM
  5. Replies: 2
    Last Post: 04-12-2004, 01:37 AM

Tags for this Thread