-
Notifications
You must be signed in to change notification settings - Fork 1
/
primes.c
347 lines (277 loc) · 8.34 KB
/
primes.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define QUEUE_SIZE 10
//Type of the circular queue elements
typedef unsigned long QueueElem;
//semaphore for sinalizing the prime calculation end
sem_t primeCalculation;
//number chosen by the user, primes calculated up to this value
int maxNumber = 0;
//number of active threads
int threadsRunning = 0;
//pointer to the first available position in the
//final primes array
int arrayPointer = 0;
//mutexes for managing the writing in the shared memory
//and the number of threads counter
pthread_mutex_t sharedMemoryMutex;
pthread_mutex_t threadsRunningMutex;
//prototypes
void *initial_thread(void *arg);
void *filter_thread(void *arg);
int compareFunction(const void * a, const void * b);
//------------------------------------------------------------------------------------------
// Struct for representing a "circular queue"
// Space for the queue elements will be allocated dinamically by queue_init()
typedef struct
{
QueueElem *v; // pointer to the queue buffer unsigned int capacity; // queue capacity
unsigned int capacity;
unsigned int first; // head of the queue
unsigned int last; // tail of the queue
sem_t empty; // semaphores and mutex for implementing the
sem_t full; // producer-consumer paradigm
pthread_mutex_t mutex;
} CircularQueue;
//------------------------------------------------------------------------------------------
// Allocates space for circular queue 'q' having 'capacity' number of elements
// Initializes semaphores & mutex needed to implement the producer-consumer paradigm
// Initializes indexes of the head and tail of the queue
// Returns 0 for success, 1 for failed queue initialization
int queue_init(CircularQueue **q, unsigned int capacity) // TO DO: change return value
{
*q = (CircularQueue *) malloc(sizeof(CircularQueue));
if(q == NULL) {
return 1;
}
sem_init(&((*q)->empty), 0, capacity);
sem_init(&((*q)->full), 0, 0);
pthread_mutex_init(&((*q)->mutex), NULL);
(*q)->v = (QueueElem *) malloc(capacity * sizeof(QueueElem));
if((*q)->v == NULL) {
return 1;
}
(*q)->capacity = capacity;
(*q)->first = 0;
(*q)->last = 0;
return 0;
}
//------------------------------------------------------------------------------------------
// Inserts 'value' at the tail of queue 'q'
void queue_put(CircularQueue *q, QueueElem value)
{
sem_wait((sem_t *) &q->empty);
pthread_mutex_lock(&q->mutex);
q->v[q->last] = value;
q->last = (q->last+1)%q->capacity;
pthread_mutex_unlock(&q->mutex);
sem_post((sem_t *) &q->full);
}
//------------------------------------------------------------------------------------------
// Removes element at the head of queue 'q' and returns its 'value'
QueueElem queue_get(CircularQueue *q)
{
sem_wait((sem_t *) &q->full);
pthread_mutex_lock(&q->mutex);
QueueElem value;
value = q->v[q->first];
q->first = (q->first+1)%q->capacity;
pthread_mutex_unlock(&q->mutex);
sem_post((sem_t *) &q->empty);
return value;
}
//------------------------------------------------------------------------------------------
// Frees space allocated for the queue elements and auxiliary management data
// Must be called when the queue is no longer needed
void queue_destroy(CircularQueue *q)
{
free(q->v);
}
int main(int argc, char *argv[]) {
if(argc != 2) {
printf("Usage: ./primes <number>\n");
exit(-1);
}
maxNumber = strtol(argv[1], NULL, 0);
double neededSpace = 1.2 * (maxNumber / log(maxNumber));
long neededSpaceAproximation = ceil(neededSpace) + 1;
sem_init(&primeCalculation, 0, 0);
key_t key;
int shmid;
char *data;
//allocates the required space on a shared memory segment
key = ftok("primesMemory", 0);
if ((shmid = shmget(key, sizeof(QueueElem)*neededSpaceAproximation, IPC_CREAT | IPC_EXCL | SHM_R | SHM_W)) == -1) {
perror("shmget");
exit(1);
}
// attach to the segment to get a pointer to it //
data = (char *) shmat(shmid, 0, 0);
if (data == (char *) -1) {
perror("shmat");
exit(1);
}
//closes the pointer
if (shmdt((char*)data) == -1) {
perror("shmdt1");
exit(1);
}
pthread_mutex_init(&sharedMemoryMutex, NULL);
pthread_mutex_init(&threadsRunningMutex, NULL);
//creates the initial thread
pthread_t initialThread;
pthread_create(&initialThread, NULL, initial_thread, NULL);
////pthread_join(initialThread, NULL);
sem_wait(&primeCalculation);
int *pt;
key = ftok("primesMemory", 0); /* uses the same key */
shmid = shmget(key, 0, 0);
pt = (int *) shmat(shmid, 0, 0);
//sorts the final primes array
qsort(pt,arrayPointer,sizeof(int),compareFunction);
int i;
printf("%d calculated primes up to %d: \n\n", arrayPointer, maxNumber);
for(i=0; i<arrayPointer; i++) {
printf("%d\n", pt[i]);
}
//clears the shared memory segment
if (shmctl(shmid, IPC_RMID, 0)) {
perror("shmctl");
exit(1);
}
//detaches the pointer from the shared memory segment
if (shmdt((char*)pt) == -1) {
perror("shmdt1");
exit(1);
}
return 0;
}
void *initial_thread(void *arg)
{
key_t key;
int shmid;
int *pt;
key = ftok("primesMemory", 0); /* uses the same key */
shmid = shmget(key, 0, 0);
pt = (int *) shmat(shmid, 0, 0);
//sets the next prime pointer to the first available position
arrayPointer=0;
//sets the first prime as 2
pt[ arrayPointer ] = 2;
//increments the pointer
arrayPointer++;
//close the shared memory
if (shmdt((char*)pt) == -1) {
perror("shmdt1");
exit(1);
}
if(maxNumber>2) {
CircularQueue *q;
queue_init(&q,QUEUE_SIZE);
pthread_t filterThread;
pthread_create(&filterThread, NULL, filter_thread, q);
//fills in the first filtering queue with odd numbers
QueueElem i;
for(i=3; i<=maxNumber; i++) {
if(i%2 != 0) {
queue_put(q, i);
}
}
queue_put(q, 0);
//pthread_join(filterThread, NULL);
} else {
sem_post(&primeCalculation);
}
return NULL;
}
void *filter_thread(void *arg)
{
key_t key;
int shmid;
int *pt;
//increments the threads counter
pthread_mutex_lock(&threadsRunningMutex);
threadsRunning++;
pthread_mutex_unlock(&threadsRunningMutex);
key = ftok("primesMemory", 0); /* uses the same key */
shmid = shmget(key, 0, 0);
pt = (int *) shmat(shmid, 0, 0);
CircularQueue *q = arg;
//gets the first element of the Circular Queue that was
//passed as an argument
QueueElem first_number = queue_get(q);
//if the first element of the queue is
//bigger than the square root of the
//chosen number, the sieving is completed
//and all remaining numbers are primes
if(first_number > sqrt(maxNumber)) {
//pushes the first element into the
//final primes list
pthread_mutex_lock(&sharedMemoryMutex);
pt[ arrayPointer ] = first_number;
arrayPointer++;
pthread_mutex_unlock(&sharedMemoryMutex);
//pushes all other elements into the
//final primes list
QueueElem i = queue_get(q);
while(i != 0) {
pthread_mutex_lock(&sharedMemoryMutex);
pt[ arrayPointer ] = i;
arrayPointer++;
pthread_mutex_unlock(&sharedMemoryMutex);
i = queue_get(q);
}
queue_destroy(q);
while(threadsRunning>1) {
printf("Waiting...\n");
printf("threadsRunning = %d\n", threadsRunning);
}
sem_post(&primeCalculation);
} else {
//adds the first number to the prime list
//increases the next prime pointer
pthread_mutex_lock(&sharedMemoryMutex);
pt[ arrayPointer ] = first_number;
arrayPointer++;
pthread_mutex_unlock(&sharedMemoryMutex);
CircularQueue *processQueue;
queue_init(&processQueue,QUEUE_SIZE);
pthread_t filterThread;
pthread_create(&filterThread, NULL, filter_thread, processQueue);
QueueElem i = queue_get(q);
//the next filtering queue is filled with
//all numbers except the multiples of the
//prime calculated in this filtering thread
while(i != 0) {
if(i%first_number != 0) {
queue_put(processQueue, i);
}
i = queue_get(q);
}
queue_put(processQueue, 0);
//pthread_join(filterThread, NULL);
queue_destroy(q);
}
if (shmdt((char*)pt) == -1) {
perror("shmdt1");
exit(1);
}
pthread_mutex_lock(&threadsRunningMutex);
threadsRunning--;
pthread_mutex_unlock(&threadsRunningMutex);
return NULL;
}
int compareFunction(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}