#include #include #include #include using namespace std; // to pass multiple arguments typedef struct str_thdata { int thread_no; char message[100]; } thdata; // Thread functions are member functions of this class class print_message { public: print_message () {} ~print_message () {} void *print_message_function1 ( void *ptr ) { thdata *data; data = (thdata *) ptr; // type cast to a pointer to thdata int i; for (i=0;i<10;i++) { printf("Thread %d says %s \n", data->thread_no, data->message); } pthread_exit(0); } void *print_message_function2 ( void *ptr ) { thdata *data; data = (thdata *) ptr; // type cast to a pointer to thdata int i; for (i=0;i<10;i++) { printf("Thread %d says %s \n", data->thread_no, data->message); } pthread_exit(0); } }; // This is a helper class for thread1 function class thread_launcher1 { public: thread_launcher1(print_message *obj, void *arg) : p_obj(obj), p_arg(arg) {} void *launch () { p_obj->print_message_function1(p_arg); } print_message *p_obj; void *p_arg; }; // This is a helper class for thread2 function class thread_launcher2 { public: thread_launcher2(print_message *obj, void *arg) : p_obj(obj), p_arg(arg) {} void *launch () { p_obj->print_message_function2(p_arg); } print_message *p_obj; void *p_arg; }; // This is a helper function for thread1 function void *launch_member_function1(void *obj) { thread_launcher1 *mylauncher = reinterpret_cast (obj); mylauncher->launch(); } // This is a helper function for thread2 function void *launch_member_function2(void *obj) { thread_launcher2 *mylauncher = reinterpret_cast (obj); mylauncher->launch(); } int main() { pthread_t thread1, thread2; thdata data1, data2; // initialize data to pass to thread 1 data1.thread_no = 1; strcpy(data1.message, "Hello"); // initialize data to pass to thread 2 data2.thread_no = 2; strcpy(data2.message, "World"); // a class that has thread functions as member functions print_message thread_func; // helper classes to call thread functions thread_launcher1 launcher1 (&thread_func, (void *) &data1); thread_launcher2 launcher2 (&thread_func, (void *) &data2); // create threads 1 and 2 pthread_create (&thread1, NULL, launch_member_function1, (void *) &launcher1); pthread_create (&thread2, NULL, launch_member_function2, (void *) &launcher2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); exit(0); }