Download c source code

 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
// Copyright 2018,2023 Jeisson Hidalgo CC-BY-4.0
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "array.h"

void print_array(const char* name, const array_t array);
void test_arrays(array_t array1, array_t array2);
void* test_array(void* data);

int main(void) {
  array_t array1 = array_create(100);
  array_t array2 = array_create(100);

  test_arrays(array1, array2);

  print_array("array1", array1);
  print_array("array2", array2);

  array_destroy(array1);
  array_destroy(array2);

  return 0;
}

void print_array(const char* name, const array_t array) {
  printf("%s: %zu elements\n", name, array_get_count(array));
  fflush(stdout);
}

void test_arrays(array_t array1, array_t array2) {
  srand((unsigned)((unsigned)time(NULL) + (unsigned)clock()));

  const size_t thread_count = 10 + rand() % 20;
  pthread_t* threads = (pthread_t*) malloc(thread_count * sizeof(pthread_t));

  for (size_t current = 0; current < thread_count; ++current) {
    pthread_create(threads + current, NULL, test_array,
        current % 2 ? array2 : array1);
  }

  for (size_t current = 0; current < thread_count; ++current) {
    pthread_join(threads[current], NULL);
  }

  free(threads);
}

void* test_array(void* data) {
  array_t array = (array_t)data;

  const size_t count = 1000 + rand() % 10000;
  for (size_t index = 0; index < count; ++index) {
    size_t num = rand() % 100;
    if (num >= 10) {
      array_append(array, (void*)(num));
    } else {
      num += rand() % 90;
      if (array_find_first(array, (void*)num, 0) != array_not_found) {
        array_remove_first(array, (void*)num, 0);
      }
    }
  }

  return NULL;
}