C++ stringstream in multithreaded environment
807575Feb 19 2009 — edited Feb 23 2009We are using a lot of stringstream objects in multiple locations in our code. The objects are not shared across threads but still program crashes in multithreaded environment. The investigation shows that the program crashes when we use both insertion & extraction operators (stringstream ::operator << and stringstream ::operator >> ). The program crashes at random locations, always pointing to stringstream in our code. We receive SIGBUS, or SIGSEGV or (sometimes) SIGABRT signals.
We need to know how to use stringstream in Multithreaded environment.
Any help will be highly appreciated.
Versions:
Compiler Version: CC: Sun C++ 5.9 SunOS_sparc Patch 124863-05 2008/06/03
Machine: SunOS bear 5.10 Generic_127111-11 sun4u sparc SUNW,Sun-Fire-V490
/usr/lib/sparcv9/libCstd.so.1: Sun SUNWlibC SunOS 5.10 Patch 119963-08 2006/09/20
Following is the test program (creates 20 threads & does insertion-extraction) & Makefile below it.:
{color:#0000ff}#include <string>
#include <sstream>
#include <pthread.h>
#include <thread.h>
#include <vector>
using namespace std;
extern "C" void* ThreadFunc( void* p )
{
for(int i=0 ; i < 1000000 ; i++){
string str("dummy");
stringstream buf;
buf << "Dummy Data " << i ;
buf >> str;
}
return NULL;
}
int main (int argc, char** argv)
{
try {
pthread_t thread;
vector<pthread_t> threads;
for(int i=0; i < 20 ; i++) {
pthread_create(&thread, NULL,ThreadFunc, NULL);
threads.push_back(thread);
}
int rc;
void* status;
for(int t=0; t < 10; t++) {
rc = pthread_join(threads[t], &status);
if (rc) {
// cout << "ERROR in joining thread " << threads[t] << endl;
return (-1);
}
//cout << "Completed joining thread " << threads[t] << " with status " << (long)status << endl;
}
} catch (...) {
//cout << "some exception\n";
}
return 0;
}
{color}
////////Makefile/////////////
{color:#ff00ff}CC=/appl/toolbox/studio12-July08/SUNWspro/bin/CC
CPP =${CC} -m64 -mt -xarch=sparcvis2 -g
OFILES = ${SOURCE:.cpp=.o}
PROG = stringstreamtest
SOURCE = main.cpp
{color}
{color:#ff00ff}${PROG}:${OFILES}
${CPP} ${OFILES} -o $@
%.o:%.cpp
${CPP} -c $< -o $@
{color}
{color:#ff00ff}clean:
${RM} *~
${RM} *.o
${RM} -r ${PROG}
${RM} -f .make.state
.KEEP_STATE:{color}