> but if the reconfiguring-thread is working, both arrays must not read the array....
So what's to stop the reconfigure thread from making changes half-way though a read?
As in
Code:
// "If the mutex is claimed, wait, but if it is not, do not claim the mutex"
if ( waitIfLockedElseCarryon() ) {
// stuff
// In another thread, reconfigure does pthread_mutex_lock successfully and changes the data
// more stuff, now with a broken data structure.
}
Assuming the amount of overall work is non-trivial, the cost of a lock/unlock pair is (on my machine) of the order of 1uS.
Code:
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <time.h>
pthread_mutex_t mutex;
int main()
{
if (pthread_mutex_init(&mutex, NULL) < 0) {
perror("Could not initialize Mutex");
}
struct timespec t0,t1,t2,t3;
clock_gettime(CLOCK_MONOTONIC, &t0);
clock_gettime(CLOCK_MONOTONIC, &t1);
pthread_mutex_lock(&mutex);
clock_gettime(CLOCK_MONOTONIC, &t2);
pthread_mutex_unlock(&mutex);
clock_gettime(CLOCK_MONOTONIC, &t3);
long clockread = t1.tv_nsec - t0.tv_nsec;
long locktime = t2.tv_nsec - t1.tv_nsec;
long unlocktime = t3.tv_nsec - t2.tv_nsec;
printf("Overhead=%ld, lock=%ld, unlock=%ld\n", clockread, locktime, unlocktime);
pthread_mutex_destroy(&mutex);
return 0;
}
# These are nanosecond times.
$ ./a.out
Overhead=206, lock=803, unlock=958
$ ./a.out
Overhead=156, lock=784, unlock=665
$ ./a.out
Overhead=190, lock=900, unlock=724
$ ./a.out
Overhead=194, lock=734, unlock=710
$ ./a.out
Overhead=161, lock=790, unlock=679
> What if in exactly this moment the array gets changed by an thread, which realizes that a socket has been closed and wants to remove the element out of the array.
I might design a different solution.
Look, if you're using threads, you NEED a good design.
Half-baked deployment of a thread here, or a lock there will just make a complete disaster you will never fully debug.