|
-
December 6th, 2008, 05:33 AM
#1
c++ allocators thread-safe?
Hi,
I have been experiencing crashes in a heavily multi-threaded application (up to 1000 threads), that were always related to memory allocation (usually a std::string being resized).
Now, if I execute the following example on the target system (a red hat 9 => old thread-model) it causes std::bad_allocs as well as SIGABRT and sometimes segmentation faults if I set the number of threads high enough (>=250).
On my development machine (an up-to-date linux) it doesn't.
EDIT: Almost forgot: All systems I tested on have multi-core CPUs.
My question is: Is the code correct and there is something wrong with the target system or am I doing something wrong?
Sorry that I couldn't reduce the code further, but if I remove anything, the errors disappear or become a lot less frequent.
Code:
#include <pthread.h>
#include <string>
#include <iostream>
#include <sstream>
pthread_t Threads[NUM_THREADS];
void f(std::string &a)
{
std::istringstream test(a);
char i;
test >> i;
std::string r = '\"'+std::string("d")+'\"';
}
void * startThread(void *)
{
for(;;) {
std::string s2("test");
f(s2);
int size = rand() % 100000 + 1;
try {
char* b = new char[size + 1];
memset(b, rand() % 255, size);
b[size] = '\0';
s2 = b;
delete [] b;
} catch (const std::exception& e) {
std::cout << "failed to allocate array of size " << size + 1 << ":" << e.what() << std::endl;
}
}
return NULL;
}
int main()
{
srand(time(NULL));
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_create(&Threads[i], NULL, startThread, NULL);
}
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(Threads[i], NULL);
}
return 0;
}
compile with "g++ -DNUM_THREADS=250 -Wall -o test test.cpp -pthread -Wall"
Any help would be greatly appreciated.
Last edited by Tannin; December 6th, 2008 at 05:44 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|