Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <semaphore.h>
- #include <pthread.h>
- pthread_mutex_t mutex;
- pthread_cond_t full;
- char buffer[10];
- void *Producer() {
- int i;
- pthread_mutex_lock(&mutex);
- for(i = 0; i <= 10; i++){
- buffer[i] = i;
- printf("Produced: %d\n", buffer[i]);
- if(i==10) {
- pthread_cond_signal(&full);
- printf("Signal sent\n");
- }
- sleep(1);
- }
- pthread_mutex_unlock(&mutex);
- pthread_exit(NULL);
- }
- void *Consumer() {
- int j;
- pthread_mutex_lock(&mutex);
- for(j = 0; j <= 10; j++) {
- j = buffer[j];
- printf("Consumed: %d\n", buffer[j]);
- sleep(1);
- }
- pthread_cond_wait(&full,&mutex);
- pthread_mutex_unlock(&mutex);
- pthread_exit(NULL);
- }
- int main() {
- pthread_t t1, t2;
- void *t;
- pthread_create(&t1, NULL, Producer, NULL);
- pthread_create(&t2, NULL, Consumer, NULL);
- pthread_join(t1, &t);
- printf("Producer finished.\n");
- pthread_join(t2, &t);
- printf("Consumer finished. \n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement