Write a program, open 3 threads, the IDs of the 3 threads are a, B, C, each thread prints its own ID on the screen 10 times, the output must be displayed in the order of ABC, such as: Abcabc .... recursion in turn.
Use conditional variables to implement:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
Static pthread_mutex_t Mtx=pthread_mutex_initializer;
Static pthread_cond_t CondA;
Static pthread_cond_t condb;
Static pthread_cond_t Condc;
void* Threada (void *arg)
{
int a = 10;
while (a--)
{
Sleep (2);
printf ("A begin.\n");
Pthread_mutex_lock (&MTX);
printf ("A wait.\n");
Pthread_cond_wait (&CONDC,&MTX);
printf ("a.\n");
Pthread_mutex_unlock (&MTX);
Pthread_cond_signal (&conda);
}
}
void* threadb (void *arg)
{
int b=10;
while (b--)
{
Sleep (2);
printf ("B begin.\n");
Pthread_mutex_lock (&MTX);
printf ("B wait.\n");
Pthread_cond_wait (&CONDA,&MTX);
printf ("b.\n");
Pthread_mutex_unlock (&MTX);
Pthread_cond_signal (&CONDB);
}
}
void* threadc (void *arg)
{
int c=10;
while (c--)
{
Sleep (2);
printf ("C begin.\n");
Pthread_mutex_lock (&MTX);
printf ("C wait.\n");
Pthread_cond_wait (&CONDB,&MTX);
printf ("c.\n");
Pthread_mutex_unlock (&MTX);
Pthread_cond_signal (&CONDC);
}
}
int main (void *arg)
{
pthread_t Tida;
pthread_t Tidb;
pthread_t TIDC;
Pthread_cond_init (&conda,null);
Pthread_cond_init (&condb,null);
Pthread_cond_init (&condc,null);
Pthread_create (&tida,null,&threada,null);
Pthread_create (&tidb,null,&threadb,null);
Pthread_create (&tidc,null,&threadc,null);
printf ("main begin. \ n ");
Sleep (4);
Pthread_cond_signal (&CONDC);
Pthread_join (Tida,null);
Pthread_join (Tidb,null);
Pthread_join (Tidc,null);
return 0;
}
Linux Multithreaded Programming Example 2