1.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
//互斥锁
pthread_mutex_t mutex;
//条件变量
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int flag=0;
void *callback1(void *arg)
{
while(1)
{
//上锁
pthread_mutex_lock(&mutex);
if(flag!=0)
{
pthread_cond_wait(&cond,&mutex);
}
else
{
临界区/
printf("a");
flag=1;
临界区/
}
//唤醒睡在指定条件变量上的线程
pthread_cond_signal(&cond);
//解锁
pthread_mutex_unlock(&mutex);
}
}
void *callback2(void *arg)
{
while(1)
{
//上锁
pthread_mutex_lock(&mutex);
if(flag!=1)
{
pthread_cond_wait(&cond,&mutex);
}
else
{
临界区/
printf("b");
flag=2;
临界区/
}
//唤醒睡在指定条件变量上的线程
pthread_cond_signal(&cond);
//解锁
pthread_mutex_unlock(&mutex);
}
}
void *callback3(void *arg)
{
while(1)
{
//上锁
pthread_mutex_lock(&mutex);
if(flag!=2)
{
pthread_cond_wait(&cond,&mutex);
}
else
{
临界区/
printf("c");
putchar(10);
flag=0;
临界区/
}
//唤醒睡在指定条件变量上的线程
pthread_cond_signal(&cond);
//解锁
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, const char *argv[])
{
//创建互斥锁
pthread_mutex_init(&mutex,NULL);
//创建线程1
pthread_t tid1;
int res1=pthread_create(&tid1,NULL,callback1,NULL);
if(res1!=0)
{
fprintf(stderr,"error\n");
return -1;
}
//创建线程2
pthread_t tid2;
int res2=pthread_create(&tid2,NULL,callback2,NULL);
if(res2!=0)
{
fprintf(stderr,"error\n");
return -1;
}
//创建线程3
pthread_t tid3;
int res3=pthread_create(&tid3,NULL,callback3,NULL);
if(res3!=0)
{
fprintf(stderr,"error\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
运行结果:
2.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <semaphore.h>
char c=0;
//信号灯
sem_t sem1;
sem_t sem2;
off_t offset=0;
int fd;
int size;
void *callback1(void *arg)
{
while(1)
{
sem_wait(&sem1);
ssize_t ret=read(fd,&c,sizeof(c));
if(ret<0)
{
perror("read");
return NULL;
}
else if(ret==0)
{
break;
}
sem_post(&sem2);
}
sem_post(&sem2);
pthread_exit(NULL);
}
void *callback2(void *arg)
{
int len=0;
while(len<size)
{
sem_wait(&sem2);
ssize_t ret=write(1,&c,sizeof(c));
if(ret<0)
{
perror("write");
return NULL;
}
len=lseek(fd,0,SEEK_CUR);
sem_post(&sem1);
}
sem_post(&sem1);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
fd=open("./mutex.c",O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
size=lseek(fd,0,SEEK_END);
lseek(fd,0,SEEK_SET);
//创建信号灯
if(sem_init(&sem1,0,1)<0)
{
return -1;
}
if(sem_init(&sem2,0,0)<0)
{
return -1;
}
//创建线程1
pthread_t tid1;
int res1=pthread_create(&tid1,NULL,callback1,NULL);
if(res1!=0)
{
fprintf(stderr,"error\n");
return -1;
}
//创建线程2
pthread_t tid2;
int res2=pthread_create(&tid2,NULL,callback2,NULL);
if(res2!=0)
{
fprintf(stderr,"error\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
//销毁互斥锁
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}