// First program with std::thread #include #include // Callable object - thread entry point void hello() { std::cout << "Hello, Thread!\n"; } int main() { // Create an std::thread object // Pass the entry point function to the constructor std::thread thr(hello); // Wait for the thread to complete thr.join(); } #include #include #include using namespace std; const int nplayers{4}; const int max_number{30}; string player_names[] = {"Abdul", "Bart", "Claudia", "Divya"}; void speak() { for (int n = 1; n <= max_number; ++n) { string player = player_names[(n-1)%nplayers]; cout << player << " says "; if (n % 3 == 0 && n % 5 == 0) { cout << "fizzbuzz!"; } else if (n % 3 == 0) { cout << "fizz!"; } else if (n % 5 == 0) { cout << "buzz!"; } else { cout << n; } cout << endl; } } int main() { // speak(); thread game{speak}; game.join(); } // Unsynchronized threads which make conflicting accesses. // But where is the shared memory location? #include #include void print(std::string str) { // A very artificial way to display a string! for (int i = 0; i < 5; ++i) { std::cout << str[0] << str[1] << str[2] << std::endl; } } int main() { std::thread thr1(print, "abc"); std::thread thr2(print, "def"); std::thread thr3(print, "xyz"); // Wait for the tasks to complete thr1.join(); thr2.join(); thr3.join(); } #include #include #include std::mutex coutMutex; // Mutex for synchronizing access to std::cout void print(std::string str) { // A very artificial way to display a string! for (int i = 0; i < 5; ++i) { std::unique_lock lock(coutMutex); // Lock to synchronize access to std::cout std::cout << str[0] << str[1] << str[2] << std::endl; lock.unlock(); // Unlock after using std::cout } } int main() { std::thread thr1(print, "abc"); std::thread thr2(print, "def"); std::thread thr3(print, "xyz"); // Wait for the tasks to complete thr1.join(); thr2.join(); thr3.join(); return 0; }