1

The code in question is:

void insertIntoFinalArray(char * string) {
    sem_wait(&insert);
    if (finalarray == NULL) finalarray = (char **) malloc(sizeof(char *));
    else finalarray = (char **) realloc(finalarray, ((size_final + 1) * sizeof(char *)));

    finalarray[size_final] = (char *) malloc(sizeof(string) + 1);
    strcpy(finalarray[size_final], string);
    size_final++;
    sem_post(&insert);
}

insert is initialized as sem_init(&insert, 0, 0); EDIT: this is supposed to be sem_init(&insert, 0, 1) I was code stirring and just didn't set it back... it doesn't work either way.

As I understand it, the threads should wait at sem_wait() until the value is greater than zero. However, the debug shows multiple threads within the function. ugggg

So am I just not understanding what a semaphore does or ?

Edit: OS X doesn't support unnamed semaphores... However, even using insert = sem_open("insert", O_CREAT, 1); allows all threads to get past my sem_wait() line.

Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62
  • And you are absolutely sure you aren't posting somewhere else in the code because otherwise nothing is getting in there to begin with. BTW what debugger is that? Is it from an IDE? – Duck Oct 10 '13 at 23:51
  • no nowhere else am I posting http://pastebin.com/Q1Pdi6bw – Tyler Sebastian Oct 11 '13 at 00:13
  • If it is initialized to a value of zero, how would anything get past the first `sem_wait`. Something is fishy here. I'd suggest posting a complete program that shows your problem. – wjl Oct 11 '13 at 00:14
  • @wjl I originally had it as sem_init(&insert, 0, 1) but I was code stirring and hadn't switched it back... also see my other comment for the full code. – Tyler Sebastian Oct 11 '13 at 00:17
  • @Duck it's xcode. It's pretty nifty, actually. – Tyler Sebastian Oct 11 '13 at 00:19
  • 4
    Oh ok, I think [this](http://stackoverflow.com/a/4136440/63743) is your problem. The comment about the debugger reminded me of osx. Xcode sure looks nice though. – Duck Oct 11 '13 at 00:29
  • nope. I open it, and then unlink it, and all threads still manage to get in. `insert = sem_open("insert", O_CREAT | O_EXCL, 1); sem_unlink("insert");` – Tyler Sebastian Oct 11 '13 at 00:49
  • 2
    Try "/insert" for the name. And check your return codes. – Duck Oct 11 '13 at 01:04
  • @Duck that worked... why did that work? – Tyler Sebastian Oct 11 '13 at 01:08
  • See the the description section in the [posix spec](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_open.html) Not sure I can explain that anyway. :) – Duck Oct 11 '13 at 01:16

1 Answers1

0

Thank you to Duck for helping me out.

Apple gcc defines sem_init in semaphores.h, but it returns -1 - it's unimplemented. That is, you cannot have unnamed semaphores. Instead, use sem_open(name, options, initial value);

Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62