1

I'm working on an assignment which involves the use of various thread synchronizing mechanisms, but the only one that's giving me a headache is pthread_barrier_t.

The idea is to implement the barrier as a checkpoint for a few threads, but they are blocking permanently.

I checked a few answers here and my implementation seems correct, even compiled and ran this simple one without any issues.

cpu.c (contains the main thread):

#include <pthread.h>
#include "../include/cpu.h"
#include "../include/units.h"

pthread_barrier_t barrier;

void cpu_boot() {
  pthread_barrier_init(&barrier, NULL, 2));
}

void *cpu_thread() {
  pthread_t unit1_thread;
  pthread_t unit2_thread;
  pthread_create(&unit1_thread, NULL, &unit1_func, NULL);
  pthread_create(&unit2_thread, NULL, &unit2_func, NULL);

  (...)

  pthread_join(unit1_thread, NULL);
  pthread_join(unit2_thread, NULL);

  pthread_exit(0);
}

units.c (contains the other threads' functions):

#include <pthread.h>
#include "../include/units.h"
#include "../include/cpu.h"

void *unitN_func() {

  (...)

  pthread_barrier_wait(&barrier);
  pthread_exit(0);
}

Some notes:

  • Both files I'm referencing have their own header file
  • I carefully removed some pieces of the code to make it shorter
  • Function bodies are mostly empty anyway, I'm waiting for the barrier to work
  • Error checks were also removed to keep the code short (no errors on execution)
  • barrier count reflects the removal of a few threads
  • barrier is externed on cpu.h

Thanks!

Community
  • 1
  • 1
  • 2
    Do you ever call `cpu_boot()`? If not, your barrier is never initialized and you most likely are invoking undefined behavior as a result. You should probably amend the code you've posted to make it a [MCVE](http://stackoverflow.com/help/mcve). What you have posted right now sort of shows some structure, but it's not very useful beyond that... – twalberg Apr 20 '15 at 17:18

0 Answers0