volatile keyword for pointer array object for network packets info container that changes frequently C

Viewed 100

I have a struct pointer array like this

   struct packets *p=(struct packets *)malloc(sizeof(struct packets)*30);

There are two steps of the program

Step 1) in producer thread I am getting network packets from RX-Ring (from Packet MMAP)

Step 2) and In consumer thread I am responding packets carrying syn=1,ack=0 received in step 1 using TX-Ring (Again Packet MMAP)

And algo s like this

Update -- I am really sorry I mis-wrote, real algorithm is like following

    main()
      pthread_create step1;// Detached thread // while loop inside
      pthread_create step2;//Detached thread  // another while loop inside
    end main

the struct packets *p is list of packets receiving and responding to IP packets. I heard about volatile objects that prevent compiler from optimization. the *p is allocated just once and I am using field inside struct packets to indicate the last operation performed on individual element of *p array (whether producer performed last operation or consumer performed last operation) from Google search of volatile objects I found following info

The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.26-Apr-2020

So I like to know is it ok if I use struct packets *p pointer as volatile since values will frequently changed.

I am coding in C

And allocation of struct packets *p pointer array happens just once

Update

*p is global. and allocated in receiver just once like pthread_once

I am also using conditional variable to signal sending thread that packets are received

Sorry again

1 Answers

Is the packet buffer being accessed by multiple threads? If not, you do not need to use the volatile keyword since the compiler can keep track of changes to this variable, and in fact, it is probably a good idea to allow the compiler to optimize normally. The fact that it 'frequently changes' is completely irrelevant.

On the other hand, if you are indeed accessing the buffer from multiple threads (or say, an interrupt service routine), or some other process modifies the data unbeknown to you, then you should declare the buffer as volatile, but also use something like a mutex or semaphore to prevent race conditions.

PS: After your update to the question, it definitely looks like the second case is true. Recommend to declare it as volatile, along with using proper synchronization.

(This answer that was shared in one of the comments has more detailed info on what problem volatile addresses.)

Related