#include #include #include using namespace std; #include #include #include #include // !!!!!!!!!! Mutex declaration !!!!!!!!!! mutex my_lock; /** * Thread to execute * * PARAMETERS * - id, thread identifier * - msg, message to print */ void thread_code(int id, string msg) { int n_repeat = 5; while (n_repeat) { // !!!!!!!!!! LOCK !!!!!!!!!! my_lock.lock(); cout << "thread(" << id <<") "; cout << ", msg=[" << msg << "]"; cout << ", repeat=" << n_repeat << endl; // !!!!!!!!!! UNLOCK !!!!!!!!!! my_lock.unlock(); --n_repeat; this_thread::sleep_for(std::chrono::seconds(1)); } } /** * Main function */ int main() { // array of threads thread *threads[10]; // create threads for (int i=0; i<10; ++i) { char msg[20]; sprintf(msg, "coucou %d", 100 + rand() % 100); threads[i] = new thread(thread_code, i, msg ); } // perform join for (int i=0; i<10; ++i) { threads[i]->join(); } cout << "!!! END OF PROGRAM !!!!" << endl; pthread_exit(NULL); return 0; }