#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <unistd.h>
char buf[] = "1234567";
sem_t sem;
sem_t sem1;
void* dayin(void* arg)
{
while(1)
{
if(sem_wait(&sem1)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
printf("%s\n",buf);
if(sem_post(&sem)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
void* daozhi(void* arg)
{
int i,j;
while(1)
{
if(sem_wait(&sem)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
for(i=0,j=strlen(buf)-1; i<j ; i++,j--)
{
char temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
if(sem_post(&sem1)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem,0,1)<0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem1,0,0)<0)
{
perror("sem_init1");
return -1;
}
pthread_t A,B;
pthread_create(&A,NULL,daozhi,(void*)buf);
pthread_create(&B,NULL,dayin,(void*)buf);
pthread_join(A,NULL);
pthread_join(B,NULL);
sem_destroy(&sem);
return 0;
}
2024/3/4
最新推荐文章于 2024-11-07 23:24:07 发布