In DPDK, the operation of the atomic weight is encapsulated. Such as
typedefstruct{
volatileint32_t cnt;/**< An internal counter value. */
}rte_atomic32_t;
But a lot of people use it, often as follows
rte_atomic32_t pkt_count;
pkt_count.cnt +=......
This is actually very insecure in multi-threading. Example:
#include<pthread.h>
#include<stdio.h>
volatileint test=0;
//pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
void* print_xs (void* used)
{
//pthread_rwlock_wrlock(&rwlock);
test=test+2;
//pthread_rwlock_unlock(&rwlock);
sleep(1);
//pthread_rwlock_wrlock(&rwlock);
test=test+3;
//pthread_rwlock_unlock(&rwlock);
}
int main (){
pthread_t thread_id[100];
int data=0;
int i=0;
for(i=0; i<100; i++){
pthread_create (&(thread_id[i]), NULL, print_xs, NULL);
}
for(i=0; i<100; i++){
pthread_join(thread_id[i],NULL);
}
printf("%d\n",test);
return-1;
}
The test code, as above, defines thevOlatileand is executed without locking. Execution results are random, not 500. Excerpt from Wikipedia:in theProgramming, especially inC language,C++,C#and theJavalanguage, use the volatile keyword to declare theVariableorObjecttypically have special properties related to optimizations, multithreading. Usually,
volatilekeywords are used to prevent (pseudo) compilers from being optimized for code that cannot be "changed by the code itself" (Variables/objects). In the C language,
volatileThe keyword can be used to remind the compiler that variables defined later can change at any time, so the compiled program reads the data directly from the variable address each time it needs to store or read the variable. Without the volatile keyword, the compiler might optimize reading and storage, may temporarily use the value in the register, and if the variable was updated by another program, there would be an inconsistency .
Null
Volatile does not guarantee thread safety