1.线程同步实例代码 semaphore.c
#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<time.h>
pthread_t tid1,tid2;
sem_t enablepush,enablepop;
pthread_mutex_t mtx;
volatile int buffer[100];
volatile int count=0;
void* producerFun(void*){
int item;
struct timespec t;
t.tv_nsec=10000000UL;
t.tv_sec=0UL;
for(int i=0;i<100;++i){
item=rand()%10000;
sem_wait(&enablepush);
pthread_mutex_lock(&mtx);
buffer[count]=item;
printf("Producer push %d into buffer[%d]\n",item,count++);
pthread_mutex_unlock(&mtx);
sem_post(&enablepop);
if(i/10%2==0)
t.tv_sec=1UL;
else
t.tv_sec=0UL;
nanosleep(&t,NULL);
}
return 0;
}
void* consumerFun(void*){
int item;
struct timespec t;
t.tv_nsec=1000000UL;
t.tv_sec=0UL;
for(int i=0;i<100;++i)
{
sem_wait(&enablepop);
pthread_mutex_lock(&mtx);
item=buffer[--count];
printf("Consumer pop %d from buffer[%d]\n",item,count);
pthread_mutex_unlock(&mtx);
sem_post(&enablepush);
if(i/10%2==1)
t.tv_sec=1UL;
else
t.tv_sec=0UL;
nanosleep(&t,NULL);
}
return 0;
}
int main(){
pthread_create(&tid1,NULL,producerFun,NULL);
pthread_create(&tid2,NULL,consumerFun,NULL);
sem_init(&enablepush,0,100);
sem_init(&enablepop,0,0);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&enablepush);
sem_destroy(&enablepop);
pthread_mutex_destroy(&mtx);
return 0;
}
2.进程同步实例代码 producer.c和consumer.c
//producer.c
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<semaphore.h>
#include<stdbool.h>
sem_t *empty, *full;
int main(){
empty=sem_open("empty", O_CREAT|O_RDWR, 0666,0);//Create sem_t empty and init 0
if(SEM_FAILED==empty){
perror("sem_open_empty");
exit(EXIT_FAILURE);
}
full =sem_open("full", O_CREAT|O_RDWR, 0666,1);//Create sem_t full and init 1
if(SEM_FAILED==full){
perror("sem_open_full");
exit(EXIT_FAILURE);
}
int count=0;
while(true){
sem_wait(full);
//Critical Region where proucer goes into and consumer being blocked
printf("\033[2J\033[H\033[38;2;255;255;125mProducer goes into Critial Region which protected by semaphore for the %dth time.\n",count++);
sem_post(empty);
sleep(1);
}
return 0;
}
//consumer.c
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<semaphore.h>
#include<stdbool.h>
sem_t *empty, *full;
int main(){
empty=sem_open("empty",0);//Access to existing sem_t empty
if(SEM_FAILED==empty){
perror("sem_open_empty");
exit(EXIT_FAILURE);
}
full =sem_open("full" ,0);//Access to existing sem_t full
if(SEM_FAILED==full){
perror("sem_open_full");
exit(EXIT_FAILURE);
}
int count=0;
while(true){
sem_wait(empty);
//Critical Region where consumer goes into and producer being blocked
printf("\033[2J\033[H\033[38;2;125;255;255mConsumer goes into Critical Region which protected by semaphore for the %dth time.\n",count++);
sem_post(full);
}
return 0;
}
运行结果: