#include #include #include #include #include #include #include #include static volatile int thread_exit = 0; int thread_delay (unsigned int time_ms) { usleep (time_ms * 1000); return 0; } void * thread_func1 (void *arg) { int n; n = (int)arg; fprintf (stdout, "Thread #%d enters tf1...\n", n); fflush (stdout); while (1) { //thread_delay (250 + (rand () * 256 / RAND_MAX)); thread_delay (313); fprintf (stdout, "W"); fflush (stdout); if (thread_exit) break; } fprintf (stdout, "Leaving thread func1!\n"); fflush (stdout); return (void *) 1UL; } void * thread_func2 (void *arg) { int n; n = (int)arg; fprintf (stdout, "Thread #%d enters tf2...\n", n); while (1) { //thread_delay (250 + (rand () * 256 / RAND_MAX)); thread_delay (257); fprintf (stdout, "R"); fflush (stdout); if (thread_exit) break; } fprintf (stdout, "Leaving thread func2!\n"); fflush (stdout); return (void *) 2UL; } int main (int argc, const char **argv) { int rv; pthread_t thr1, thr2; void *tr1, *tr2; // spawn two threads..... rv = pthread_create (&thr1, NULL, thread_func1, (void *)1UL); if (rv) fprintf (stderr, "err %d create thr1\n", errno); rv = pthread_create (&thr2, NULL, thread_func2, (void *)2UL); if (rv) fprintf (stderr, "err %d create thr2\n", errno); fflush (stderr); // Only actually run if both threads started ok! if (!rv) while (1) { // Control thread: wait for user input and execute it char dummy[8]; fprintf (stdout, "Press return/enter to terminate....."); fflush (stdout); // fflush (stdin); // scanf ("%*[^\r\n]%1[\r\n]", &dummy[0]); scanf ("%1c", &dummy[0]); fprintf (stderr, "****AFTER SCANF\n"); // never loop... this is just a test after all.... break; } thread_exit = 1; rv = pthread_join (thr1, &tr1); if (rv) fprintf (stderr, "pthr join errno1 %d\n", errno); else fprintf (stderr, "exit ok\n"); rv = pthread_join (thr2, &tr2); if (rv) fprintf (stderr, "pthr join errno1 %d\n", errno); else fprintf (stderr, "exit 2 ok\n"); fprintf (stderr, "thread exticodes $%8p $%8p\n", tr1, tr2); return 0; }