// based on a program written by Dr. Art DuPre #include #include #include void *task(void *arg) { for (int i=0;i<1000;i++) { cout << (char *)arg; if(i%50==5)cout<<'\n'; cout.flush(); } return NULL; } int main() { pthread_t t1; if ( pthread_create(&t1, NULL, task, (void *)"1") != 0 ) { // pthread_create takes 4 arguments, 1st is a pointer to a // pthread_t, the second is a pointer to thread attributes // (we pass in NULL to use default attributes. third slot is // for a (pointer to a) function. This function has to have // return type void* and also a single argument of type void*. // The 4th (& last) argument is the arguement to be passed into // the function (task in this case). This should be a pointer, // and we can cast this pointer to type void *. cout << "pthread_create() error" << endl; abort(); } // for (long j=0; j<100; ++j) // for (long i=0; i<1000000; ++i); task((void *)"2"); pthread_join(t1,NULL); // if the main program thread is allowed to exit, then all child // threads are destroyed & may not actually do their work. So // use pthread_join to wait for the thread. }