/* This program spawns NUM_THREADS threads, each of which count from 0 to LOOP_NUM (exclusive) For example, when NUM_THREADS = 4 and LOOP_NUM = 5, 4 threads will be spawned and the output of each thread will be counting from 0 to 4. Don't forget to compile with the -pthread flag! */ #include #include using std::cout; using std::cerr; using std::endl; const int NUM_THREADS = 4; const int LOOP_NUM = 5; // This is the routine that is executed by each of the threads spawned by main(). // Counts from 0 to LOOP_NUM (exclusive). // Parameter arg is a pointer to an int representing the thread number. void *thread_main(void *arg) { int *num = reinterpret_cast(arg); for (int i = 0; i < LOOP_NUM; i++) { cout << "[cthread: " << *num << "] " << i << endl; } delete num; return nullptr; } // Main spawns each thread with pthread_create() and tells them to execute thread_main() int main(int argc, char** argv) { // an array of all of our threads pthread_t thds[NUM_THREADS]; // spawn threads for (int i = 0; i < NUM_THREADS; i++) { int *num = new int(i); // create new thread and tell it to execute thread_main() with argument num if (pthread_create(&thds[i], nullptr, &thread_main, num) != 0) { cerr << "pthread_create failed" << endl; } } // by calling pthread_exit, if main() finishes before the threads // it will not terminate the execution of the threads pthread_exit(nullptr); // because we call pthread_exit, we should not see this statement printed cout << "Unreachable statement" << endl; return 0; }