Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force a variable to be stored in the cache in C?

Tags:

c

I just had a phone interview where I was asked this question. I am aware of ways to store in register or heap or stack, but cache specifically?

like image 604
Shivkrish22 Avatar asked Aug 09 '10 21:08

Shivkrish22


People also ask

Can volatile variable be cached?

Unlike other variables, volatile variables are written to and read from the main memory. The CPU does not cache the value of a volatile variable.

Does cache store data permanently?

Cache memory is not to be confused with the broader term cache. Caches are temporary stores of data that can exist in both hardware and software. Cache memory refers to the specific hardware component that allows computers to create caches at various levels of the network.

What is caching in C?

Caching is a separate memory, yes, and it has it's own addresses, but when the CPU caches memory lines from RAM, it keeps a record of what RAM-addresses the memory was on, and keeps a map between RAM-address and cache-address. From the point of view of your program, the address is the same.


2 Answers

Not in C as a language. In GCC as a compiler - look for __builtin_prefetch.

You might be interested in reading What every programmer should know about memory.

Edit:

Just to clear some confusion - caches are physically separate memories in hardware, but not in software abstraction of the machine. A word in a cache is always associated with address in main memory. This is different from the CPU registers, which are named/addressed separately from the RAM.

like image 187
Nikolai Fetissov Avatar answered Sep 30 '22 19:09

Nikolai Fetissov


In C, as in as defined by the C standard? No.

In C, as in some specific implementation on a specific platform? Maybe.

like image 24
Matti Virkkunen Avatar answered Sep 30 '22 20:09

Matti Virkkunen