Sign in to follow this  
GCoda

pthread_create crashes

Recommended Posts

Hi, I was trying to create thread in linux but for some reason this simple code crashes:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "unistd.h"
#include <pthread.h>

using namespace std;

void *threadRoutine(void *arg)  // this never gets called
{
 cout<<"in the thread routine..."<<endl;
 return NULL;
}

int main(int argc, char *argv[])
{
 long arg;
 pthread_t thread;
 cout<<"creating new thread"<<endl;
 int retCode = pthread_create(&thread,NULL,threadRoutine,&arg); // crash in here
 if(retCode != 0)
  cout<<"failed to run thread"<<endl;
 cout<<"ending main thread"<<endl;

return -1;
}

I don't understand, everything seems to be fine, right? I'm using GCC 4.01 and the console output says its buffer overflow. Thanks.

Share this post


Link to post
Share on other sites
GCoda,

It's been a while since I've used pthreads, so this maybe completely wrong ... but:

Are you building with the correct GCC flags for pthreads? i.e. somthing like "-mt -pthead" multi-threaded and pthread support.

The posted code has (possibly) two further issues:
- cout may not be thread safe (I'm not sure about this but seem to remember having problems with it in the past)
- the main function may exit while the created thread is running, if this happens "pthread_t thread" will go out of scope and you're into undefined behaviour.

To check you're building correctly I'd take someone elses pthread example from the web and see if it works, Another Example.

Cheers

Tom

Share this post


Link to post
Share on other sites
Tom,
Thanks for your reply, you are probably right about that I need to enable the multithread support. I don't yet know how this is done but I'm sure I'll figure it out once I get the time.

And thanks again for the points you make and for the link.

Cheers.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this