方式1:
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#define MAX 10
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int flag = 1;
void *thread_A(void *arg)
{
int i = 0;
for(i = 0; i < MAX; i++)
{
pthread_mutex_lock(&mutex);
while(1 != flag)
{
pthread_cond_wait(&cond, &mutex);
}
printf("\tthread_A_id = %u", (unsigned int)pthread_self());
flag = 2;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
return NULL;
}
void *thread_B(void *arg)
{
int i = 0;
for(i = 0; i < MAX; i++)
{
pthread_mutex_lock(&mutex);
while(2 != flag)
{
pthread_cond_wait(&cond, &mutex);
}
printf("\tthread_B_id = %u", (unsigned int)pthread_self());
flag = 3;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
return NULL;
}
void *thread_C(void *arg)
{
int i = 0;
for(i = 0; i < MAX; i++)
{
pthread_mutex_lock(&mutex);
while(3 != flag)
{
pthread_cond_wait(&cond, &mutex);
}
printf("\tthread_C_id = %u\n", (unsigned int)pthread_self());
flag = 1;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t th[3];
int status;
int i;
status = pthread_create(&th[0], NULL, thread_A, NULL);
if(status != 0)
{
printf("thread create error: %d\n", strerror(errno));
}
status = pthread_create(&th[1], NULL, thread_B, NULL);
if(status != 0)
{
printf("thread create error: %d\n", strerror(errno));
}
status = pthread_create(&th[2], NULL, thread_C, NULL);
if(status != 0)
{
printf("thread create error: %d\n", strerror(errno));
}
for(i = 0; i < 3; i++)
{
pthread_join(th[i], NULL);
}
printf("\n");
return 0;
}
方式2:
#include <stdio.h>
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
#define CYCLES 10
#define THREAD_NUMS 3
int n = 0;
void *thread_fun(void *arg)
{
int param = *(int *)arg;
char c = 'A' + param;
int i = 0;
while(i++ < CYCLES)
{
pthread_mutex_lock(&mutex);
while(param != n)
{
pthread_cond_wait(&cond, &mutex);
}
printf("\tthread_%c_id=%u", c, (unsigned int)pthread_self());
n = (n+1) % THREAD_NUMS;
if(0 == n)
printf("\n");
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
return NULL;
}
int main(int argc, char*argv[])
{
int i = 0;
int arr[THREAD_NUMS];
for(i = 0; i < THREAD_NUMS; i++)
{
arr[i] = i;
}
pthread_t thread_arr[THREAD_NUMS];
for(i = 0; i < THREAD_NUMS; i++)
{
int status = pthread_create(&thread_arr[i], NULL, thread_fun, (void *)&arr[i]);
if(status != 0)
printf("thread create error!\n");
}
for(i = 0; i < THREAD_NUMS; i++)
{
pthread_join(thread_arr[i], NULL);
}
return 0;
}