Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Yes, but the original post is actually accessing two different data elements (vec[0] and vec[1]), and the discussion here is if that's safe or not. The conclusion is that it's not always safe, but most machines will be able to access "int" in a single access.
If you can be sure that the processor doesn't touch the data AROUND your access, then single writes are safe without locks.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Ok, so if we have:
Your rule doesn't cover the above, which is still possible to break.Code:short a; short b; void* foo(void* arg) { short* i = (short*)(arg); *i = rand()*10; } int main() { pthread_t t1, t2; pthread_create(&t1, NULL, foo, (void*)&a); pthread_create(&t1, NULL, foo, (void*)&b); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; }
And I'd wager that in an x86 architecture, a with vector<int> vec; &vec[0] and &vec[1] are perfectly fine to be accessed independently without locks. But it's not guaranteed in all architectures.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
You're right, naturally. Thread safety is a difficult thing.
But it's a very good general rule to remember. I think the C/C++ standard mentions such a thing, perhaps even on reads? It defines them as "condition races" I think?
But my was point was, that I would not truly consider it thread safe because it violates the basic rule of never accessing the same object from two or more threads at the same time without synchronization.
A lot of multithreaded code IS broken, because it assumes that all accesses to basic types are atomic, which is not actually guaranteed at all. And anyway, how would you implement an atomic 16-bit store on an architecture with an 8 bit bus? You can't, unless you mask interrupts and lock the bus. Masking and then unmasking interrupts every time you access a variable would be... dumb.
This is a good read on the subject of "word tearing":
http://groups.google.com/group/comp....a9c0ee17e390c/
Tru64 documentation is also an interesting read:
http://h30097.www3.hp.com/docs/base_...7.HTM#gran_sec (3.7 Granularity Considerations)
http://h30097.www3.hp.com/docs/base_...E/DOCU0008.HTM
gg
Neither the C nor the C++ standard currently even have the concept of multiple threads of execution.I think the C/C++ standard mentions such a thing, perhaps even on reads?
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law