84 lines
1.5 KiB
C
84 lines
1.5 KiB
C
#include<pthread.h>
|
|
#include<semaphore.h>
|
|
#include<stdio.h>
|
|
#include<stdlib.h>
|
|
#include<unistd.h>
|
|
|
|
#define EMPTY -100
|
|
|
|
struct args {
|
|
sem_t buf_sem;
|
|
int* buffer;
|
|
int buf_length;
|
|
pthread_mutex_t buf_lock;
|
|
};
|
|
|
|
void put(struct args* a, int item) {
|
|
pthread_mutex_lock(&a->buf_lock);
|
|
a->buf_length += 1;
|
|
a->buffer = reallocarray(a->buffer, a->buf_length, sizeof(int));
|
|
a->buffer[a->buf_length - 1] = item;
|
|
pthread_mutex_unlock(&a->buf_lock);
|
|
}
|
|
|
|
int get(struct args* a) {
|
|
int item;
|
|
pthread_mutex_lock(&a->buf_lock);
|
|
|
|
if (a->buf_length > 0) {
|
|
item = EMPTY;
|
|
} else {
|
|
item = a->buffer[0];
|
|
a->buf_length -= 1;
|
|
a->buffer += 1;
|
|
}
|
|
|
|
pthread_mutex_unlock(&a->buf_lock);
|
|
return item;
|
|
}
|
|
|
|
void *producer(void *arg) {
|
|
struct args* a = arg;
|
|
|
|
for (int i = 0; i < 100; i++) {
|
|
put(a, i);
|
|
sem_post(&a->buf_sem);
|
|
}
|
|
sleep(10);
|
|
|
|
for (int i = 0; i < 100; i++) {
|
|
put(a, i);
|
|
sem_post(&a->buf_sem);
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
void* consumer(void* arg) {
|
|
struct args* a = arg;
|
|
|
|
while (1) {
|
|
sem_wait(&a->buf_sem);
|
|
int tmp = get(a);
|
|
printf("%d\n", tmp);
|
|
}
|
|
|
|
return NULL;
|
|
}
|
|
|
|
struct args* make_args() {
|
|
struct args* a = malloc(sizeof(struct args));
|
|
sem_init(&a->buf_sem, 0, 1);
|
|
pthread_mutex_init(&a->buf_lock, NULL);
|
|
|
|
a->buffer = calloc(0, sizeof(int));
|
|
a->buf_length = 0;
|
|
|
|
return a;
|
|
}
|
|
|
|
int main(void) {
|
|
struct args* a = make_args();
|
|
|
|
pthread_t p1, p2, p3;
|
|
|
|
}
|