aboutsummaryrefslogtreecommitdiff
path: root/pa4_shared_array/test.c
blob: 14c0a3c0b73ffe3cb15570c709a666fbbfd50e0e (plain)
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
// Jack Sangdahl
// CSCI3753 SP24
// PA4 Shared Array
#include "array.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 10
#define HOSTNAME_CNT 6

array stack;
static char *data;
static char *hostnames[] = {"facebook.com", "youtube.com",   "yahoo.com",
                            "live.com",     "wikipedia.org", "msn.com"};

void *thread_produce(void *a) {
  for (int i = 0; i < HOSTNAME_CNT; i++) {
    array_put(&stack, hostnames[i]);
    printf("PUSHED: %s\n", hostnames[i]);
  }
  return NULL;
}

void *thread_consume(void *a) {
  for (int i = 0; i < HOSTNAME_CNT; i++) {
    array_get(&stack, &data);
    printf("POPPED: %s\n", data);
  }
  return NULL;
}

int main(void) {
  pthread_t *produce_threads =
      (pthread_t *)malloc(NUM_THREADS * sizeof(pthread_t));
  pthread_t *consume_threads =
      (pthread_t *)malloc(NUM_THREADS * sizeof(pthread_t));
  array_init(&stack);
  for (int i = 0; i < NUM_THREADS; i++) {
    pthread_create(&produce_threads[i], NULL, thread_produce, NULL);
    pthread_create(&consume_threads[i], NULL, thread_consume, NULL);
  }
  for (int i = 0; i < NUM_THREADS; i++) {
    pthread_join(produce_threads[i], NULL);
    pthread_join(consume_threads[i], NULL);
  }
  free(produce_threads);
  free(consume_threads);
  array_free(&stack);
  return EXIT_SUCCESS;
}