-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Multithread feature of C in consumer and producer pattern
- Loading branch information
1 parent
792ee08
commit ef12127
Showing
1 changed file
with
80 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <string.h> | ||
#include <pthread.h> | ||
#include <unistd.h> | ||
#include <time.h> | ||
#include <semaphore.h> | ||
/*gcc -o multithread multiThreading.c -lpthread*/ | ||
#define THREAD_NUM 8 | ||
|
||
sem_t semEmpty; | ||
sem_t semFull; | ||
|
||
pthread_mutex_t mutexBuffer; | ||
|
||
int buffer[10]; | ||
int count = 0; | ||
|
||
void* producer(void* args) { | ||
while (1) { | ||
// Produce | ||
int x = rand() % 100; | ||
sleep(1); | ||
|
||
// Add to the buffer | ||
sem_wait(&semEmpty); | ||
pthread_mutex_lock(&mutexBuffer); | ||
buffer[count] = x; | ||
count++; | ||
pthread_mutex_unlock(&mutexBuffer); | ||
sem_post(&semFull); | ||
} | ||
} | ||
|
||
void* consumer(void* args) { | ||
while (1) { | ||
int y; | ||
|
||
// Remove from the buffer | ||
sem_wait(&semFull); | ||
pthread_mutex_lock(&mutexBuffer); | ||
y = buffer[count - 1]; | ||
count--; | ||
pthread_mutex_unlock(&mutexBuffer); | ||
sem_post(&semEmpty); | ||
|
||
// Consume | ||
printf("Got %d\n", y); | ||
sleep(1); | ||
} | ||
} | ||
|
||
int main(int argc, char* argv[]) { | ||
srand(time(NULL)); | ||
pthread_t th[THREAD_NUM]; | ||
pthread_mutex_init(&mutexBuffer, NULL); | ||
sem_init(&semEmpty, 0, 10); | ||
sem_init(&semFull, 0, 0); | ||
int i; | ||
for (i = 0; i < THREAD_NUM; i++) { | ||
if (i > 0) { | ||
if (pthread_create(&th[i], NULL, &producer, NULL) != 0) { | ||
perror("Failed to create thread"); | ||
} | ||
} else { | ||
if (pthread_create(&th[i], NULL, &consumer, NULL) != 0) { | ||
perror("Failed to create thread"); | ||
} | ||
} | ||
} | ||
for (i = 0; i < THREAD_NUM; i++) { | ||
if (pthread_join(th[i], NULL) != 0) { | ||
perror("Failed to join thread"); | ||
} | ||
} | ||
sem_destroy(&semEmpty); | ||
sem_destroy(&semFull); | ||
pthread_mutex_destroy(&mutexBuffer); | ||
return 0; | ||
} |