Multithreading and O3 compilation in C

时间:2015-07-29 00:15:01

标签: c multithreading optimization

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

public class PriceSimulator : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged; 

    private int max, delay, priceValue;
    private Timer timer;

    public PriceSimulator(int max, int delay)
    {
        this.max = max;
        this.delay = delay;
    }
    public void Start()
    {
        timer = new Timer(CallbackProc, null, delay, delay);
    }
    private void CallbackProc(object obj)
    {
        if (++Price >= max)
            timer.Dispose();
    }
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        try
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        catch (Exception ex)
        {
            timer.Dispose();
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
    }
    public int Price 
    {
        get
        {
            return priceValue;
        }
        set
        {
            if (priceValue != value)
            {
                priceValue = value;
                NotifyPropertyChanged();
            }
        }
    }
}

I have 2 pthreads running at all times, one for each function. When i compile normally (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); } } ) This works as intended. gcc -lpthread changes SensorSignalReader and changedSignal detects it as the while loop breaks. When I compile with the ChangeDetector or flag though it feels like the variable -O3 never changes? The while loop in changedSignal runs forever while signals are being changed constantly. If I put a ChangeDetector inside there, it prints -1 all the time. There is something done by O3 that I do not understand. What is it?

1 个答案:

答案 0 :(得分:3)

It's very likely your program is experiencing undefined behaviour and you just got lucky when you didn't have optimisations switched on.

{{ render(controller('OCUserBundle:RegistrationApprenant:register',{'request': app.request}))}} 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 changedSignal'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.