How to protect a global variable shared by isr and regular function?

前端 未结 4 1590
星月不相逢
星月不相逢 2020-12-16 04:04

Let\'s say I have function 1 and an isr routine, both share and update the same flag without any lock between them. the system is single th

4条回答
  •  攒了一身酷
    2020-12-16 04:58

    This should help prevent missed interrupt. It is based on the wonderfully detailed ans from @artless_noise

    Here the ISR posts on a semaphore(non blocking call). Adding the barrier to ensure that write completes. The thread will run as many times as the semaphore is posted.

    sem = sem_open(argv[optind], flags, perms, 0); // Initialising semaphore to 0
    
    function 1:
    
    while(sem_getvalue(sem) > 0)
    {
       flag = false;
       //Avoiding the barrier if this value isnt needed by ISR
       asm volatile ("" : : : "memory"); /* gcc barrier */
       //perform action
    }
    
    isr routine:
        do something
        flag=true;
        asm volatile ("" : : : "memory"); /* gcc barrier */
        sem_post(sem);
    

提交回复
热议问题