I am working with pthreads in c++ doing the sleeping barber problem. Was just trying to initialize threads and test it out but am getting a segmentation fault at a random point in execution. Sometimes both threads are able to output and sometimes only one thread is able to output. I am struggling to find what's causing this in my current code. Any help is greatly appreciated <3
#include <iostream>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
#define NUM_THREADS 2
// Global pthread implementation of mutex lock
pthread_mutex_t mtx;
// Argument we will cast as void* for the thread function
struct Args {
  int tid;
  string type;
};
void *test_thread_function(void *args) {
  Args *local_args = (Args *)args;
  // Get the lock before entering the critical section
  pthread_mutex_lock(&mtx);
  cout << "Printing from thread " << local_args->tid << endl;
  cout << "Value of type is " << local_args->type << endl;
  // Release the lock to someone else
  pthread_mutex_unlock(&mtx);
}
int main() {
  // Create an array of threads
  pthread_t threads[NUM_THREADS];
  Args per_thread_args[NUM_THREADS];
  // Create threads
  for (int i = 0; i < NUM_THREADS; i++) {
    if (i == 0){ //barber thread creation
      per_thread_args[i].tid = 0;
      per_thread_args[i].type = "barber";
      pthread_create(&threads[i], NULL, test_thread_function, (void *)&per_thread_args[i]);
    } else { //customer thread creation
      per_thread_args[i].tid = 1;
      per_thread_args[i].type = "customer";
      pthread_create(&threads[i], NULL, test_thread_function, (void *)&per_thread_args[i]);
    }
    // Launch the threads
    /*
        Arguments:
            1.) Pointer to pthread_t
            2.) Attributes for the thread (NULL means default)
            3.) Entry routine
            4.) Arguments
    */
  }
  
  // Return code for the thread
  void *ret;
  // Wait for all threads to finish before exiting the program
  for (int i = 0; i < NUM_THREADS; i++) {
    pthread_join(threads[i], &ret);
  }
  return 0;
}