I am using std::stringstream for reading/writing binary data.
std::stringstream strm(std::stringstream::binary|std::stringstream::in|std::stringstream::out);
strm.write(...) //happens in one thread
strm.read(...) //happens in another thread
Does C++ standards guarantees that parallel read write to stringstream work? Or not.
My fstream.h file at /usr/local/pgi/linux86-64/13.10/include/CC/fstream.h contains no mention of mutex locks. Further, in programs I have written output using << operator to stringstream files can become interleaved if written at the 'same' time.
Since you're reading from and writing to the same file, I imagine the line order is important? As such, I think you want a global mutex lock between threads.
Something like:
#include ....
pthread_mutex_t FileMutex = PTHREAD_MUTEX_INITIALIZER;
std::stringstream strm(std::stringstream::binary|...)
int main()
{
blah blah
pthread_create(&threads, NULL, function, voidPtrToArguments);
blah blah
}
void *function(void *voidPtrToArguments)
{
blah blah some more
pthread_mutex_lock(&FileMutex);
strm.write(...);
pthread_mutex_unlock(&FileMutex);
}
and then the same for a function to read.
This is covered in [iostreams.threadsafety] in the Standard. The C++17 text reads:
Concurrent access to a stream object, stream buffer object, or C Library stream by multiple threads may result in a data race unless otherwise specified. [Note: Data races result in undefined behavior . —end note ]
There is no "otherwise specified" for std::stringstream
so your case would be undefined behaviour.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.