题目:
代码:
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <unistd.h>
sem_t sem1,sem2;
void* callback1(void*arg)
{
while(1)
{
if(sem_wait(&sem1)<0) //等待sem1的信号量变为可用,申请信号灯
{
perror("sem_wait");
return NULL;
}
printf("%s\n",buf);
if(sem_post(&sem2)<0) //通知sem2的线程可以进行
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
return NULL;
}
void* callback2(void*arg)
{
int i,j;
char temp;
while(1)
{
if(sem_wait(&sem2)<0)
{
perror("sem_wait");
return NULL;
}
for(i=0,j=strlen(buf)-1;i<j;i++,j--)
{
temp = buf[i];
buf[i]=buf[j];
buf[j] = temp;
}
if(sem_post(&sem1)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
return NULL;
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem1,0,1)<0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem2,0,0)<0)
{
perror("sem_init");
return -1;
}
pthread_t A,B;
pthread_create(&A,NULL,callback1,NULL);
pthread_create(&B,NULL,callback2,NULL);
pthread_detach(B);
pthread_join(A,NULL);
pthread_join (B,NULL);
if(sem_destroy(&sem1)<0)
{
perror("sem_destroy");
return -1;
}
if(sem_destroy(&sem2)<0)
{
perror("sem_destroy");
return -1;
}
return 0;
}
运行结果: