33,027
社区成员




#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t t1_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t t2_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cv_t2_ready = PTHREAD_COND_INITIALIZER;
pthread_cond_t cv_t1_ready = PTHREAD_COND_INITIALIZER;
void *t1_func();
void *t2_func();
int it1;
int it2;
int t1_ready=0;
#define NT2 5
#define N 3
#define NT1 NT2*N
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, &t1_func, NULL);
pthread_create( &thread2, NULL, &t2_func, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(0);
}
void *t1_func() /*t1 thread*/
{
for(it1=0;it1<NT1;it1++)
{
/*start to make a serial data transfer, t1 must be ahead of t2*/
if (0==(it1 % N))
{
pthread_mutex_lock( &t1_mutex );
if (1==t1_ready)
{
printf("t1 waiting on: %3d\n",it1);
pthread_cond_wait( &cv_t2_ready, &t1_mutex );
}
t1_ready = 1;
printf("t1: %3d (to t2)\n",it1);
pthread_cond_signal( &cv_t1_ready );
pthread_mutex_unlock( &t1_mutex );
}
else
{
printf("t1: %3d \n",it1);
}
}
return(NULL);
}
void *t2_func() /*t2 thread*/
{
for(it2=0;it2<NT2;it2++)
{
pthread_mutex_lock( &t1_mutex );
if (0==t1_ready)
{
printf("t2 waiting on: %3d\n",it2);
pthread_cond_wait( &cv_t1_ready, &t1_mutex );
}
t1_ready=0;
printf("t2: %3d (to t1)\n",it2);
pthread_cond_signal( &cv_t2_ready );
pthread_mutex_unlock( &t1_mutex );
}
return(NULL);
}