/* To compile (linux): gcc ptest.c -lpthread */ /* To compile (freebsd): gcc ptest.c -pthread */ /* To compile (Sun): gcc ptest.c -lpthread -lposix4 */ #include /* must be first */ #include #include /* for sleep() */ /* Thread start function. Expects a string as an argument, and prints out 10 copies of that string. */ void *Thread(void *string) { int i; for(i=0;i<10;i++) { printf("%s\n", (char *)string); /* Yield each time. This should help (though not guarantee) interleave the output of this thread and the other one. Try it with and without this next line. */ sched_yield(); } pthread_exit(NULL); } /* Main program. Creates 2 threads, which proceed to print out copies of a message. Main thread exits, leaving the two threads running. */ int main() { char *e_hello = "hello world"; char *f_hello = "bonjour monde"; pthread_t e_thread; /* Handle for english thread */ pthread_t f_thread; /* Handle for french thread */ pthread_attr_t attr; /* Thread creation attribute */ int rc; /* Out threads will not be joined, so we create them with an attribute specifying the detached state */ pthread_attr_init(&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); /* Create a thread to emit the english hello */ /* Note we pass the string to print as an argument */ rc = pthread_create(&e_thread, &attr, Thread, (void *)e_hello); if (rc) { fprintf(stderr,"Couldn't create first thread.\n"); exit(-1); } /* Create a thread to emit the french hello */ rc = pthread_create(&f_thread, &attr, Thread, (void *)f_hello); if (rc) { fprintf(stderr,"Couldn't create second thread.\n"); exit(-1); } /* Don't need our attribute object anymore */ pthread_attr_destroy(&attr); /* application will run until exit() is called, or all threads have pthread_exit()-ed. Here the main thread does a pthread exit, which leaves the two started threads still running. */ pthread_exit(NULL); }