1.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
char buf[]="1234567";
sem_t sem;
sem_t sem1;
void *callback(void *arg)
{
while(1)
{
sem_post(&sem1);
{
printf("%s\n",buf);
}
sem_post(&sem);
}
pthread_exit(NULL);
return NULL;
}
void *callback1(void *arg)
{
while(1)
{
sem_wait(&sem);
{
int i=0;
int j=6;
while(i<j)
{
char t=buf[i];
buf[i]=buf[j];
buf[j]=t;
i++;
j--;
}
}
sem_post(&sem1);
}
pthread_exit(NULL);
return 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_init");
return -1;
}
if(sem_init(&sem1,0,1)<0)
{
perror("sem_init");
return -1;
}
pthread_t tid;
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
printf("error");
return -1;
}
pthread_t tid1;
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
printf("error");
return -1;
}
while(1)
{
}
sem_destroy(&sem);
return 0;
}
2.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char c;
int t=0;
ssize_t res=2;
void* callBack(void* arg)
{
int fp=open("copy.c",O_RDONLY);
if(fp<0)
{
ERR_MSG("open");
return NULL;
}
while(1)
{
pthread_mutex_lock(&mutex);
if(t!=0)
pthread_cond_wait(&cond,&mutex);
res=read(fp,&c,1);
if(res==0)
{
pthread_exit(NULL);
}
t=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
void* callBack2(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(t!=1)
pthread_cond_wait(&cond,&mutex);
write(1,&c,1);
t=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid,tid2;
if(pthread_create(&tid,NULL,callBack,NULL)!=0)
{
fprintf(stderr,"failed\n");
return -1;
}
if(pthread_create(&tid2,NULL,callBack2,NULL)!=0)
{
fprintf(stderr,"failed\n");
return -1;
}
pthread_join(tid,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}