0

I am trying to use semaphores in C.

I have global variable: `sem_t array[5];'

And local sem_t MyArray[2]; in a function.

I initialise my semaphores.

for(i = 0; i < 5; i++)
    sem_init(&array[i], 0, 1);

I want to assign 2 of 5 semaphores from array to MyArray. So MyArray and MyArray+ 1 will be for instance array+3 and array+1 and this are the same addresses.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3402584
  • 410
  • 4
  • 8
  • 18

2 Answers2

3

The semantics of assigning or copying a sem_t object is unclear without knowing the internals of sem_t.

  • If sem_t is a simple handle or pointer, then simply taking a copy, both copies will refer to the same semaphore.

  • If sem_t is a POD structure, taking a byte-by-byte copy is possible but the copy would be a different and independent semaphore.

  • If sem_t is not POD and contains pointers, copyinmg is non-trivial.

What you probably really want is for MyArray to refer to array by being of type sem_t*:

// By initialisation
sem_t* MyArray[2] = { &array[3], &array[1] } ;

// By assignment
sem_t* MyArray[2] ;

MyArray[0] = &array[3] ;
MyArray[1] = &array[1] ;
Clifford
  • 88,407
  • 13
  • 85
  • 165
2

instead of a copy, try using pointers to the originals

sem_t* MyArray[2];

then just assign MyArray[0] = &array[1]; or whatever one you want

then use it like sem_wait(MyArray[0]); this is different than your original array which would be sem_wait(&array[1]); because the MyArray is already pointer based.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156