作業系統實驗 Lab10
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
int count=0;
void inc(void){
int i=0;
for(i=0;i<25000000;i++){
count++;
}
pthread_exit(NULL);
}
void dec(void){
int i=0;
for(i=0;i<25000000;i++){
count--;
}
pthread_exit(NULL);
}
int main(void){
int i=0;
pthread_t id[4];
pthread_create(&id[0],NULL,(void*)dec,NULL);
pthread_create(&id[1],NULL,(void*)inc,NULL);
pthread_create(&id[2],NULL,(void*)dec,NULL);
pthread_create(&id[3],NULL,(void*)inc,NULL);
for(i=0;i<4;i++)
{
pthread_join(id[i],NULL);
}
printf("\noutput is %d\n",count);
}
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
int count=0;
sem_t sem;
void inc(void){
int i=0;
for(i=0;i<25000000;i++){
sem_wait(&sem);
count++;
sem_post(&sem);
}
pthread_exit(NULL);
}
void dec(void){
int i=0;
for(i=0;i<25000000;i++){
sem_wait(&sem);
count--;
sem_post(&sem);
}
pthread_exit(NULL);
}
int main(void){
sem_init(&sem,0,1);
int i=0;
pthread_t id[4];
pthread_create(&id[0],NULL,(void*)dec,NULL);
pthread_create(&id[1],NULL,(void*)inc,NULL);
pthread_create(&id[2],NULL,(void*)dec,NULL);
pthread_create(&id[3],NULL,(void*)inc,NULL);
for(i=0;i<4;i++)
{
pthread_join(id[i],NULL);
}
printf("\noutput is %d\n",count);
sem_destroy(&sem);
return 0;
}
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include </usr/include/semaphore.h>
#define BUFF_SIZE 5
#define NP 3
#define NC 3
#define NITERS 4
typedef struct {
int buf[BUFF_SIZE];
int in;
int out;
sem_t full;
sem_t empty;
sem_t mutex;
} sbuf_t;
sbuf_t shared;
void *Producer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=0; i < NITERS; i++) {
item = i;
sem_wait(&shared.empty);
sem_wait(&shared.mutex);
shared.buf[shared.in] = item;
shared.in = (shared.in+1)%BUFF_SIZE;
printf("[P%d] Producing %d ...\n", index, item); fflush(stdout);
sem_post(&shared.mutex);
sem_post(&shared.full);
if (i % 2 == 1) sleep(1);
}
return NULL;
}
void *Consumer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=0; i < NITERS; i++) {
sem_wait(&shared.full);
sem_wait(&shared.mutex);
item = shared.buf[shared.out];
shared.out = (shared.out+1)%BUFF_SIZE;
printf(" ------> [P%d] Consuming %d ...\n", index, item); fflush(stdout);
sem_post(&shared.mutex);
sem_post(&shared.empty);
if (i % 2 == 1) sleep(1);
}
return NULL;
}
int main()
{
pthread_t idP, idC;
int index;
sem_init(&shared.full, 0, 0);
sem_init(&shared.empty, 0, BUFF_SIZE);
sem_init(&shared.mutex, 0, 1);
for (index = 0; index < NP; index++)
{
pthread_create(&idP, NULL, Producer, (void*)index);
}
for (index = 0; index < NC; index++)
{
pthread_create(&idC, NULL, Consumer, (void*)index);
}
pthread_exit(NULL);
}