A fairly basic question, but I don't see it asked anywhere.
Let's say we have a global struct (in C) like so:
struct foo {
int written_frequently1;
int read_only;
int written_frequently2;
};
It seems clear to me that if we have lots of threads reading and writing, we need a semaphore (or other lock) on the written_frequently
members, even for reading, since we can't be 100% sure that assignments to this struct will be atomic.
If we want lots of threads to read the read_only
member, and none to write, to we need a semaphore on the struct access just for reading?
(I'm inclined to say no, because the fact that the locations immediately before and after are constantly changed shouldn't affect the read_only
member, and multiple threads reading the value shouldn't interfere with each other. But I'm not sure.)
[Edit: I realize now I should have asked this question much better, in order to clarify very specifically what I meant. Naturally, I didn't really grok all of the issues involved when I first asked the question. Of course, if I comprehensively edit the question now, I will ruin all of these great answers. What I meant is more like:
struct bar {
char written_frequently1[LONGISH_LEN];
char read_only[LONGISH_LEN];
char written_frequently2[LONGISH_LEN];
};
The major issue I asked about is, since this data is part of a struct, is it at all influenced by the other struct members, and might it influence them in return?
The fact that the members were ints, and therefore writes are likely atomic, is really just a red herring in this case.]