#include #include #include #include #include // Thread body function void* run(void* arg); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; int main() { pthread_t thread1, thread2; const char *heads = "Heads"; const char *tails = "Tails"; srand(times(NULL)); // Set the random generator // Create the first thread int res = pthread_create( &thread1, // Thread identifier NULL, // Thread attributes: using defaults &run, // Thread start function (void *) heads // Parameter to be passed to thread function ); if (res != 0) { perror("Cannot create thread 1"); exit(1); } pthread_mutex_lock(&mutex); printf("Thread 1 is created.\n"); pthread_mutex_unlock(&mutex); // Create the second thread res = pthread_create(&thread2, NULL, &run, (void *) tails); if (res != 0) { perror("Cannot create thread 2"); exit(1); } pthread_mutex_lock(&mutex); printf("Thread 2 is created.\n"); pthread_mutex_unlock(&mutex); // Wait until threads terminate pthread_join( thread1, // Thread ID NULL // Location to store the return value of thread: not used ); pthread_join(thread2, NULL); pthread_mutex_destroy(&mutex); return 0; } void* run(void* arg) { int i; const char *txt = (const char *) arg; for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); printf("%s\n", txt); pthread_mutex_unlock(&mutex); //... sched_yield(); // Give time to other threads int t = rand()%2000000 + 1; // Random time in microsec usleep(t); } return NULL; }