csci3753

CSCI3753 Coursework
git clone https://git.pngu.org/csci3753
Log | Files | Refs | README

test.c (1333B)


// 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;
}