Reputation: 1637
I'm writing code that tries to detect when i signal changes from 0 to 1 as fast as possible (real time application). I have the following two functions
void *SensorSignalReader (void *arg)
{
char buffer[30];
struct timeval tv;
time_t curtime;
srand(time(NULL));
while (1) {
int t = rand() % 10 + 1; // wait up to 1 sec in 10ths
usleep(t*100000);
int r = rand() % N;
signalArray[r] ^= 1;
if (signalArray[r]) {
changedSignal = r;
gettimeofday(&tv, NULL);
timeStamp[r] = tv;
curtime = tv.tv_sec;
strftime(buffer,30,"%d-%m-%Y %T.",localtime(&curtime));
printf("Changed %5d at Time %s%ld\n",r,buffer,tv.tv_usec);
}
}
}
void *ChangeDetector (void *arg)
{
char buffer[30];
struct timeval tv;
time_t curtime;
int index;
while (1) {
while (changedSignal == -1) {} // issues with O3
gettimeofday(&tv, NULL);
index = changedSignal;
changedSignal = -1;
curtime = tv.tv_sec;
if(timeStamp[index].tv_usec>tv.tv_usec){
tv.tv_usec += 1000000;
tv.tv_sec--;
}
strftime(buffer,30,"%d-%m-%Y %T.",localtime(&curtime));
printf("Detcted %5d at Time %s%ld after %ld.%06ld sec\n---\n",index,buffer,tv.tv_usec,
tv.tv_sec - timeStamp[index].tv_sec,
tv.tv_usec - timeStamp[index].tv_usec);
}
}
I have 2 pthreads running at all times, one for each function.
When i compile normally (gcc -lpthread
) This works as intended. SensorSignalReader
changes changedSignal
and ChangeDetector
detects it as the while loop breaks. When I compile with the -O3
or flag though it feels like the variable changedSignal
never changes? The while loop in ChangeDetector
runs forever while signals are being changed constantly. If I put a printf("%d\n",changedSignal);
inside there, it prints -1 all the time. There is something done by O3 that I do not understand. What is it?
Upvotes: 0
Views: 295
Reputation: 9930
It's very likely your program is experiencing undefined behaviour and you just got lucky when you didn't have optimisations switched on.
changedSignal
appears to be a shared resource so you need to use atomic operations or some form of locking to ensure that threads won't simultaneously access it.
You can use the pthread functions for locking or gcc
's builtin functions for atomic operations.
Edit: As pointed out by Olaf, it looks like you're trying to implement a producer-consumer pattern. You might want to try implementing this by using condition variables instead of trying to reinvent it.
Upvotes: 3