Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rdemeter
GitHub Repository: rdemeter/so
Path: blob/master/lab9/rezervarebilete2.c
221 views
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <unistd.h>
4
#include <time.h>
5
#include <pthread.h>
6
#include <semaphore.h>
7
8
#define NUM_SELLERS 50
9
#define NUM_TICKETS 25000
10
11
static int numTickets = NUM_TICKETS;
12
13
pthread_mutex_t mutex;
14
15
void *sellerThread(void* arg)
16
{
17
long total = 0;
18
do {
19
pthread_mutex_lock(&mutex);
20
if(numTickets <= 0) {
21
pthread_mutex_unlock(&mutex);
22
break;
23
}
24
numTickets--;
25
26
total++;
27
28
printf("Seller %ld sold one (%d left)\n", (long) arg, numTickets);
29
pthread_mutex_unlock(&mutex);
30
} while(numTickets > 0);
31
32
printf("Seller %ld finished! (I sold %ld tickets)\n", (long) arg, total);
33
34
// alloc result on heap, not on stack!
35
long *result = malloc(sizeof(long));
36
result[0] = total;
37
pthread_exit((void*)result);
38
}
39
40
int main(void)
41
{
42
long total_sold = 0;
43
44
pthread_t tids[NUM_SELLERS];
45
46
pthread_mutex_init(&mutex, NULL);
47
48
long i;
49
for(i=0; i < NUM_SELLERS; i++) {
50
pthread_create(&tids[i], NULL, sellerThread, (void*)i);
51
}
52
53
long **results = malloc(sizeof(long) * NUM_SELLERS);
54
for(i=0; i < NUM_SELLERS; i++) {
55
pthread_join(tids[i], (void**)&results[i]);
56
total_sold += results[i][0];
57
free(results[i]);
58
}
59
free(results);
60
61
pthread_mutex_destroy(&mutex);
62
63
printf("Done %ld!\n", total_sold);
64
return 0;
65
}
66
67