#include #include #include #include using std::cout; using std::cerr; using std::endl; //A global variable accessible to all threads. int thread_count; void* Hello(void* rank); /* The function for each thread to run */ int main(int argc, char** argv) { pthread_t* thread_handles; //get the number of threads from the command line if (argc != 2) { cerr << "Error, usage: " << endl; cerr << " " << argv[0] << " " << endl; exit(1); } thread_count = atol(argv[1]); // thread_handles = malloc(thread_count * sizeof(pthread_t)); thread_handles = new pthread_t[thread_count]; long thread; for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], NULL, Hello, (void*)thread); } // cout << "Hello from the main thread" << endl; printf("Hello from the main thread!\n"); for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], NULL); } free(thread_handles); return 0; } void* Hello(void* rank) { long my_rank = (long)rank; cout << "Hello from thread " << my_rank << " of " << thread_count << endl; printf("Hello from thread %ld of %d\n", my_rank, thread_count); }