can the below c++ thread code cause a process crash on an embedded system?
similar c++ code as below is written for an embedded device. the process running on the device crashes upon start. on some other version of the device, crash is not observed. can it be related to the thread argument & thread detach being called. on normal linux desktop environment it does not crash. can anyone pls give their comments. Thanks in advance.
#include <pthread.h>
#include <iostream>
using namespace std;
#define NUM_THREADS 2
void *PrintHello(void *msg)
{
cout<<(char*)msg<<endl;
while(1)
{
printf("Hello World! It's me, thread !\n");
sleep(2);
}
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
const char* ch = "hello how r u.i'm passing argument";
for(t=0; t<NUM_THREADS; t++)
{
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)ch);
pthread_detach(threads[t]);
if (rc)
{
printf("ERROR; return code f开发者_JAVA百科rom pthread_create() is %d\n", rc);
exit(-1);
}
}
return 0;
}
Yes.
The C++ standard library, by default, is not thread-safe... stream objects like cout
in particular.
It may or may not have anything to do with the system being embedded. It's possible that the standard library implementation for the desktop system is more thread-safe, or it just happens to be implemented slightly differently, or perhaps you just got [un]lucky that you did not observe any undesired behaviour when testing on the desktop.
精彩评论