1.
#include <myhead.h>
char c;
int i=1;
int flag=0;
pthread_mutex_t m;
pthread_cond_t cond;
void *READ()
{
int f1=open("./sem.c",O_RDONLY);
int size=lseek(f1,0,SEEK_END);
printf("%ld\n",size);
lseek(f1,0,SEEK_SET);
for(i;i<=size;i++)
{
pthread_mutex_lock(&m);
if(flag!=0)
{
pthread_cond_wait(&cond,&m);
// printf("1\n");
}
// printf("2\n");
read(f1,&c,1);
flag=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&m);
}
close(f1);
}
void *WRITE()
{
while(1)
{pthread_mutex_lock(&m);
if(flag!=1)
{
pthread_cond_wait(&cond,&m);
// printf("3\n");
}
printf("%c",c);
flag=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&m);}
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
pthread_mutex_init(&m,NULL);
pthread_cond_init(&cond,NULL);
if(pthread_create(&tid1,NULL,READ,NULL)!=0)
{
printf("create wrong\n");
}
if(pthread_create(&tid2,NULL,WRITE,NULL)!=0)
{
printf("create wrong\n");
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&m);
pthread_cond_destroy(&cond);
return 0;
}
2.
#include <myhead.h>
sem_t sema;
sem_t semb;
sem_t semc;
void* fun1()
{
while(1)
{
sem_wait(&semc);
printf("A");
sem_post(&sema);
}
}
void* fun2()
{
while(1)
{
sem_wait(&sema);
printf("B");
sem_post(&semb);
}
}
void* fun3()
{
while(1)
{
sem_wait(&semb);
printf("C\n");
sem_post(&semc);
}
}
int main(int argc, const char *argv[])
{
sem_init(&sema,0,0);
sem_init(&semb,0,0);
sem_init(&semc,0,1);
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
{
printf("create wrong\n");
}
if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
{
printf("create wrong\n");
}
if(pthread_create(&tid3,NULL,fun3,NULL)!=0)
{
printf("create wrong\n");
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
sem_destroy(&sema);
sem_destroy(&semb);
sem_destroy(&semc);
return 0;
}
3.
char buf[] = "1234567";
sem_t sem1, sem2;
void invert(void)
{
int i = 0, j = strlen(buf) - 1;
char temp;
while (i < j) {
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
i++;
j--;
}
}
void* t1(void* arg)
{
while (1) {
sem_wait(&sem1);
puts(buf);
sem_post(&sem2);
}
}
void* t2(void* arg)
{
while (1) {
sem_wait(&sem2);
invert();
sem_post(&sem1);
}
}
int main(int argc, const char* argv[])
{
if (sem_init(&sem1, 0, 1) != 0)
PRINT_ERR("sem1_init");
if (sem_init(&sem2, 0, 0) != 0)
PRINT_ERR("sem2_init");
pthread_t t1_id, t2_id;
if (0 != pthread_create(&t1_id, NULL, t1, NULL))
return -1;
if (0 != pthread_create(&t2_id, NULL, t2, NULL))
return -1;
while (1) {
}
return 0;
}