summaryrefslogtreecommitdiff
path: root/pgm5/counter.c
blob: 26735b4053a1ca0d78b8f72c961ced8b66f2a751 (plain) (blame)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
/*
 * counter.c
 * Adam Carpenter - 2017 - acarpent - acarpenter@email.wm.edu
 * Utilizes code from P. Kearns
 * Utilizes code from linuxthreads demonstration "prodcons.c"
 */


// **** Library inclusions ****
#include<errno.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<unistd.h>


// **** Definitions for counter ****
#define FALSE           0
#define LEN_LINE        2048
#define LEN_FILENAME    4096
#define MAX_THREADS     26
#define TRUE            1
#define USAGE           "counter: usage: counter -b num_lines -t max_counters -d file_delay -D thread_delay [file]...\n"


// **** Structure declarations ****
struct prodConBuff {
    /*
     * struct prodConBuff
     */
     pthread_mutex_t bufferLock;// Mutex ensures exclusive access to buffer.
     int readPos;               // Position for reading.
     int writePos;              // Position for writing.
     pthread_cond_t notEmpty;   // Signaled when buffer isn't empty.
     pthread_cond_t notFull;    // Signaled when buffer isn't full.
    //  char *lines[];
     char **lines;             // Array of strings serves as data container.
};

struct NODE {
    /*
     * struct NODE
     */
     char *word; // char *word or word[LEN_LINE]
     long count;
     struct NODE *next;
};

struct linkedList {
    /*
     * struct linkedList
     */
     pthread_mutex_t listLock;  // Mutex ensures exclusive access to linked list.
     struct NODE *head;         // Pointer to first node in list.
};


// **** Global variables ****
static char nextThread;
static int fileDelay;
static int maxCounters;
static int moreStuff;
static int numLines;
static int threadDelay;
static pthread_t threadPool[MAX_THREADS]; // Bad Threadpool.
struct prodConBuff buffer;
struct linkedList evenList;
struct linkedList oddList;


// **** Structure initializations ****
static void initBuffer(struct prodConBuff *buffer) {
    /*
     * initBuffer() initializes the buffer structure to an empty array ready for
     * producer-consumer actions.
     * The buffer of lines is initialized to NULL. As the program runs, if
     * slots are empty they will be malloc'd to fit given lines being inserted
     * into the buffer, and freed as they are taken out.
     */
    int i;

    pthread_mutex_init(&buffer->bufferLock, NULL);
    pthread_cond_init(&buffer->notEmpty, NULL);
    pthread_cond_init(&buffer->notFull, NULL);
    buffer->readPos = 0;
    buffer->writePos = 0;
    buffer->lines = (char **) calloc(numLines, LEN_LINE);

    for (i = 0; i < numLines; i++) {
        buffer->lines[i] = (char *) calloc(LEN_LINE, sizeof(char));
    }

    if (numLines == 1) {
        buffer->lines[0][0] = '\0';
    }
}

static void initLinkedList(struct linkedList *list) {
    /*
     * initLinkedList() initializes the linked list structure (its lock and its
     * head node.)
     */
    pthread_mutex_init(&list->listLock, NULL);
    list->head = NULL;
}


// **** Modifier and thread functions ****
static void sleeper(const struct timespec *req, struct timespec *rem) {
    // Researched methods of maintaining nanosleep times online and
    // found an interesting method using recursion that was similar to this.

    struct timespec newRem;

    if (nanosleep(req, rem) < 0) {
        sleeper(rem, &newRem);
    }

}

static void quitThread() {
    /*
     * quitThread()
     */
    #ifdef atcdebug
    fprintf(stderr, "counter: thread quit because no more stuff.\n");
    #endif

    nextThread--;
    pthread_exit(NULL);
}

static int putInBuffer(struct prodConBuff *buffer, char *line) {
    /*
     * putInBuffer()
     */
    int newThread;

    newThread = FALSE;
    pthread_mutex_lock(&buffer->bufferLock);

    // If buffer is full, spawn a new counter thread.
    if ((buffer->writePos + 1) % numLines == buffer->readPos) {
        newThread = TRUE;
    }

    // Wait until buffer isn't full anymore.
    while ((buffer->writePos + 1) % numLines == buffer->readPos) {
        pthread_cond_wait(&buffer->notFull, &buffer->bufferLock);

        #ifdef atcdebug
        fprintf(stderr, "reader: waiting for space...\n");
        #endif
    }

    #ifdef atcdebug
    fprintf(stderr, "reader: gonna insert in slot: %d\n", buffer->writePos);
    #endif

    // Copy the text into the next slot in the buffer.
    strncpy(buffer->lines[buffer->writePos], line, LEN_LINE);
    buffer->writePos++;

    if (buffer->writePos >= numLines) {
        buffer->writePos = 0;
    }

    #ifdef atcdebug
    fprintf(stderr, "reader: buffer is now: {  ");
    int i;
    for (i = 0; i < numLines; i++) {
        if (i == buffer->writePos) {
            fprintf(stderr, "*");

        }

        fprintf(stderr, "%s  ", buffer->lines[i]);

    }
    fprintf(stderr, "}\n\n");
    #endif

    // Signal buffer isn't empty anymore and unlock mutex.
    pthread_cond_signal(&buffer->notEmpty);
    pthread_mutex_unlock(&buffer->bufferLock);
    return newThread;
}

static int putInSingleBuffer(struct prodConBuff *buffer, char *line) {
    /*
     * putInSingleBuffer(0)
     */
    int newThread;

    pthread_mutex_lock(&buffer->bufferLock);
    newThread = FALSE;

    // If slot is taken, spawn a new counter thread
    if (buffer->lines[0][0] != '\0') {
        newThread = TRUE;
    }

    // Wait until slot isn't full anymore.
    while (buffer->lines[0][0] != '\0') {
        pthread_cond_wait(&buffer->notFull, &buffer->bufferLock);
    }

    // Insert line into buffer.
    strncpy(buffer->lines[buffer->writePos], line, LEN_LINE);

    // Signal buffer slot isn't empty anymore and unlock mutex.
    pthread_cond_signal(&buffer->notEmpty);
    pthread_mutex_unlock(&buffer->bufferLock);
    return newThread;
}

static void getFromBuffer(struct prodConBuff *buffer, char *line) {
    /*
     * getFromBuffer()
     */

    pthread_mutex_lock(&buffer->bufferLock);

    // If buffer is 'empty' and nothing more will be written, quit.
    if (!moreStuff && buffer->readPos == buffer->writePos) {
        quitThread();
    }

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

    // Wait until buffer isn't empty anymore.
    while (buffer->readPos == buffer->writePos) {
        #ifdef atcdebug
        fprintf(stderr, "counter: waiting for stuff...\n");
        #endif

        pthread_cond_wait(&buffer->notEmpty, &buffer->bufferLock);
    }

    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);

    #ifdef atcdebug
    fprintf(stderr, "counter: getting from slot: %d\n", buffer->readPos);
    #endif

    // Get line from buffer and advance read position.
    strncpy(line, buffer->lines[buffer->readPos], LEN_LINE);
    buffer->readPos++;
    if (buffer->readPos >= numLines) buffer->readPos = 0;

    #ifdef atcdebug
    fprintf(stderr, "counter: buffer is now: {  ");
    int i;
    for (i = 0; i < numLines; i++) {
        if (i == buffer->readPos) {
            fprintf(stderr, "*");

        }

        fprintf(stderr, "%s  ", buffer->lines[i]);

    }
    fprintf(stderr, "}\n\n");
    #endif

    // Signal buffer isn't full anymore and unlock mutex.
    pthread_cond_signal(&buffer->notFull);
    pthread_mutex_unlock(&buffer->bufferLock);
}

static void getFromSingleBuffer(struct prodConBuff *buffer, char *line) {
    /*
     * getFromSingleBuffer();
     */

    pthread_mutex_lock(&buffer->bufferLock);
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

    // Wait until buffer isn't empty anymore.
    while (buffer->lines[0][0] == '\0') {

        // If buffer slot is empty and nothing more will be written to it, quit.
        if ((buffer->lines[0][0] == 0) && !moreStuff) {
            quitThread();
        }

        pthread_cond_wait(&buffer->notEmpty, &buffer->bufferLock);
    }

    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);

    // Get line from buffer slot.
    strncpy(line, buffer->lines[0], LEN_LINE);
    buffer->lines[0][0] = '\0';

    // Signal buffer slot isn't full anmore and unlock mutex.
    pthread_cond_signal(&buffer->notFull);
    pthread_mutex_unlock(&buffer->bufferLock);
}

static void putInList(struct linkedList *list, char *word) {
    /*
     * putInList()
     */
    struct NODE *current;
    struct NODE *new;

    pthread_mutex_lock(&list->listLock);

    #ifdef atcdebug
    fprintf(stderr, "counter: gonna insert into list\n");
    #endif

    if (list->head == NULL) {
        new = (struct NODE *) malloc(sizeof(struct NODE));
        new->word = (char *) malloc(strlen(word));
        strcpy(new->word, word);
        new->count = 1;
        list->head = new;
    }
    else {

        for (current = list->head; current != NULL; current = current->next) {

            if (strcmp(current->word, word) == 0) {
                // Word already in list; update count.
                current->count++;
                break;
            }
            else if (current->next != NULL
                    && strcmp(word, current->next->word) < 0) {
                // Insert in front of next-greatest lexiographical word.
                new = (struct NODE *) malloc(sizeof(struct NODE));
                new->word = (char *) malloc(strlen(word));
                strcpy(new->word, word);
                new->count = 1;
                new->next = current->next;
                current->next = new;
                break;
            }
            else if (current->next == NULL) {
                // Reached the end; Insert at back of list.
                new = (struct NODE *) malloc(sizeof(struct NODE));
                new->word = (char *) malloc(strlen(word));
                strcpy(new->word, word);
                new->count = 1;
                new->next = NULL;
                current->next = new;
                break;
            }

        }

    }

    #ifdef atcdebug
    fprintf(stderr, "counter: list is now: {");
    current = list->head;
    while (current != NULL) {
        fprintf(stderr, "%s->", current->word);
        current = current->next;
    }
    fprintf(stderr, "}\n\n");
    #endif

    pthread_mutex_unlock(&list->listLock);
}

static void printList(struct linkedList *list) {
    /*
     * printList()
     */
     struct NODE *current;

     // For debugging purposes and future implementations, lock the list.
     pthread_mutex_lock(&list->listLock);

     // Print the word of every node in the list.
     for (current = list->head; current != NULL; current = current->next) {
         printf("Count: %ld Word: %s\n", current->count, current->word);
     }

     pthread_mutex_unlock(&list->listLock);
}

static void freeList(struct linkedList *list) {
    /*
     * freeList()
     */
    struct NODE *current;
    struct NODE *temp;

    // For debugging purposes and future implementations, lock the list.
    pthread_mutex_lock(&list->listLock);

    // Free every node in the list.
    while (current != NULL) {
        temp = current;
        current = current->next;
        free(temp);
    }

    pthread_mutex_unlock(&list->listLock);
}

static void * counterThread(void * arg) {
    /*
     * counterThread()
     */
    char name;
    char line[LEN_LINE];
    char *token;
    struct timespec requestedTime;
    struct timespec remainingTime;

    name = (char) arg;
    requestedTime.tv_sec = threadDelay / 1000;
    requestedTime.tv_nsec = threadDelay % 1000 * 1000000;
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);

    #ifdef atcdebug
    fprintf(stderr, "counter: name == %c, numLines == %d, threadDelay == %d\n", name, numLines, threadDelay);
    #endif

    while (TRUE) {

        // Sleep for allotted time.
        sleeper(&requestedTime, &remainingTime);

        if (numLines == 1) {
            getFromSingleBuffer(&buffer, line);
        }
        else {
            getFromBuffer(&buffer, line);
        }

        // Get the first word in the line.
        token = strtok(line, " ");

        // With each word, see if there are an even or odd number of characters
        // and insert the word into the designated list. Then print the name
        // of the thread on stdout.
        while (token != NULL) {

            if (strlen(token) % 2 == 0) {
                putInList(&evenList, token);

                #ifndef atcdebug
                printf("%c ", name);
                #endif

            }
            else {
                putInList(&oddList, token);

                #ifndef atcdebug
                printf("%c ", name);
                #endif

            }

            token = strtok(NULL, " ");
        }

    }

    return NULL;
}

static void createThread() {
    /*
     * createThread()
     */

     // Would a new thread put us over the maximum allowed?
     // If not, create another counter thread as requested.

     if (((nextThread - 'a') < maxCounters)) {
         #ifdef atcdebug
         fprintf(stderr, "reader: creating thread, name == %c\n", nextThread);
         #endif

         pthread_create(&threadPool[nextThread - 'a'], NULL, counterThread, (void *) nextThread);
         nextThread++;
     }

}


// **** Main ****
int main(int argc, char *argv[]) {
    /*
     * main() acts as the reader thread, and therefore the producer.
     */
    char line[LEN_LINE];
    int i;
    FILE *textFile;
    struct timespec requestedTime;
    struct timespec remainingTime;

    // Get command line args.
    if (argc < 10) {
        fprintf(stderr, USAGE);
        exit(1);
    }

    numLines = maxCounters = fileDelay = threadDelay = -1;
    i = 1;
    errno = 0;

    while (argv[i] && i < 9) {

        // Get numLines.
		if (strcmp(argv[i], "-b") == 0) {
            i++;

			if (argv[i]) {
                numLines = strtol(argv[i], NULL, 10);

                if (errno != 0 || numLines <= 0) {
                    fprintf(stderr, "counter: num_lines must be a positive, non-zero integer.\n");
                    exit(1);
                }

            }
            else {
                fprintf(stderr, USAGE);
                exit(1);
            }

		}
        // Get maxCounters.
		else if (strcmp(argv[i], "-t") == 0) {
            i++;

            if (argv[i]) {
                maxCounters = strtol(argv[i], NULL, 10);

                if (errno != 0 || maxCounters <= 0 || maxCounters > 26) {
                    fprintf(stderr, "counter: max_counters must be a positive, non-zero integer no greater than 26.\n");
                    exit(1);
                }

            }
            else {
                fprintf(stderr, USAGE);
                exit(1);
            }

        }
        // Get fileDelay.
        else if (strcmp(argv[i], "-d") == 0) {
            i++;

            if (argv[i]) {
                fileDelay = strtol(argv[i], NULL, 10);

                if (errno != 0 || fileDelay < 0) {
                    fprintf(stderr, "counter: file_delay must be a positive integer.\n");
                    exit(1);
                }

            }
            else {
                fprintf(stderr, USAGE);
                exit(1);
            }

        }
        // Get threadDelay.
        else if (strcmp(argv[i], "-D") == 0) {
            i++;

            if (argv[i]) {
                threadDelay = strtol(argv[i], NULL, 10);

                if (errno != 0 || threadDelay < 0) {
                    fprintf(stderr, "counter: thread_delay must be a positive integer.\n");
                    exit(1);
                }

            }
            else {
                fprintf(stderr, USAGE);
                exit(1);
            }

        }
        else {

            if (numLines < 0 || maxCounters < 0
                    || fileDelay < 0 || threadDelay < 0) {
                fprintf(stderr, USAGE);
                exit(1);
            }

        }

        i++;
	}

    #ifdef atcdebug
    fprintf(stderr, "reader: numLines = %d, maxCounters = %d, fileDelay = %d, "
        "threadDelay = %d\n", numLines, maxCounters, fileDelay, threadDelay);
    #endif

    // Set up thread environment.
    initBuffer(&buffer);
    initLinkedList(&evenList);
    initLinkedList(&oddList);
    nextThread = 'a';
    moreStuff = TRUE;

    // Start up first counter (consumer) thread.
    createThread();

    // **** Reader (producer) thread ****
    textFile = NULL;
    requestedTime.tv_sec = threadDelay / 1000;
    requestedTime.tv_nsec = threadDelay % 1000 * 1000000;

    while (argv[i]) {

        // Open each file given in argv[].
        if (!(textFile = fopen(argv[i], "r"))) {
            fprintf(stderr, "counter: could not open %s\n", argv[i]);
        }
        else {

            // Read each line in the file and insert it into the buffer.
            while (fgets(line, LEN_LINE, textFile)) {
                // Strip newline.
                line[strcspn(line, "\n")] = '\0';

                if (numLines == 1) {

                    // Attempt to create a new thread if function says
                    // buffer was full.
                    if (putInSingleBuffer(&buffer, line) == TRUE) {
                        createThread();
                    }

                }
                else {

                    // Attempt to create a new thread if put function says
                    // buffer was full.
                    if (putInBuffer(&buffer, line) == TRUE) {
                        createThread();
                    }

                }

                // Sleep for allotted time.
                while (nanosleep(&requestedTime, &remainingTime) == -1) {
                    requestedTime = remainingTime;
                }

            }

            fclose(textFile);
        }

        i++;
    }

    // Let counter threads know that there won't be any more input and wait
    // for threads to finish before printing and terminating.
    moreStuff = FALSE;

    sleep(2);

    for (i = 0; i < MAX_THREADS; i++) {

        if (threadPool[i]) {
            pthread_cancel(threadPool[i]);
        }

    }

    printf("\n==== Words with an even number of letters ====\n");
    printList(&evenList);
    printf("\n==== Words with an odd  number of letters ====\n");
    printList(&oddList);
    freeList(&evenList);
    freeList(&oddList);
    exit(0);
}