Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <time.h>
- #include <limits.h>
- #include <semaphore.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #define THREADS 8
- int aantal_tickets = 500;
- int totaal_aantal_verkocht = 0;
- void sell_tickets(pthread_mutex_t *mtx);
- struct thread_info {
- pthread_t thread_id;
- pthread_mutex_t *mtx;
- };
- static void * thread_start(void *arg) {
- struct thread_info* tinfo = arg;
- sell_tickets(tinfo->mtx);
- }
- int main (int argc, char ** argv) {
- srand(time(NULL));
- struct thread_info *tinfo;
- tinfo = calloc(THREADS, sizeof(struct thread_info));
- pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
- for(int tnum = 0; tnum < THREADS; tnum++) {
- tinfo[tnum].mtx = &mtx;
- pthread_create(&tinfo[tnum].thread_id, NULL, &thread_start, &tinfo[tnum]);
- }
- for(int tnum = 0; tnum < THREADS; tnum++) {
- pthread_join(tinfo[tnum].thread_id, NULL);
- }
- printf("totaal tickets verkocht: %d\n", totaal_aantal_verkocht);
- }
- void sell_tickets(pthread_mutex_t *mtx) {
- int aantal_verkocht = 0;
- while(aantal_tickets > 0) {
- // pthread_mutex_lock(mtx);
- if(aantal_tickets > 0) {
- aantal_tickets--;
- aantal_verkocht++;
- }
- // pthread_mutex_unlock(mtx);
- sleep(rand()%3);
- }
- totaal_aantal_verkocht+= aantal_verkocht;
- printf("aantal verkocht: %d\n", aantal_verkocht);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement