#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; } int rand_r (unsigned int *seed) { long k; long s = (long)(*seed); if (s == 0) s = 0x12345987; k = s / 127773; s = 16807 * (s - k * 127773) - 2836 * k; if (s < 0) s += 2147483647; (*seed) = (unsigned int)s; return (int)(s & RAND_MAX); } void * thread_func1 (void *arg) { int n; #ifdef RANDOM unsigned int randseed1 = 0xf00dface; #endif n = (int)arg; fprintf (stdout, "Thread #%d enters tf1...\n", n); fflush (stdout); while (1) { #ifdef RANDOM thread_delay (250 + (rand_r (&randseed1) * 256 / RAND_MAX)); #else thread_delay (313); #endif 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; #ifdef RANDOM unsigned int randseed2 = 0xf00dface; #endif n = (int)arg; fprintf (stdout, "Thread #%d enters tf2...\n", n); while (1) { #ifdef RANDOM thread_delay (250 + (rand_r (&randseed2) * 256 / RAND_MAX)); #else thread_delay (257); #endif 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; }