#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
int a[10] = {1,2,3,4,5,6,7,8,9,10};
sem_t sem1, sem2;
void *thread_func1(void *arg)
{
int i;
while (1)
{
sem_wait(&sem1);
for (i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
sem_post(&sem2);
//sleep(1);
}
}
void *thread_func2(void *arg)
{
int i;
while (1)
{
sem_wait(&sem2);
for (i = 9; i >= 0; i--)
printf("%d ", a[i]);
printf("\n");
sem_post(&sem1);
//sleep(1);
}
}
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
int err;
sem_init(&sem1, 0, 1); //生产者信号量:1
sem_init(&sem2, 0, 0); //消费者信号量:0
err = pthread_create(&thread1, NULL, thread_func1, NULL);
if (err != 0)
{
fprintf(stderr, "pthread_create1: %s\n", strerror(err));
return -1;
}
err = pthread_create(&thread2, NULL, thread_func2, NULL);
if (err != 0)
{
fprintf(stderr, "pthread_create2: %s\n", strerror(err));
return -1;
}
while (1)
sleep(1);
return 0;
}
02-10
874