Hello everyone!
I am using pthreads on Linux with C++ which spawns one thread and (tries to) play music. However, as soon as the program gets to the point where any function tries to use any member in the class, program seg-faults.
Here -

class audio
{
public:
     int play(char *filename);
     int test;

private:
     static void	*audioThread( void *ptr );
     void		playAudio(void);
     pthread_t 		playThread;
}

void *audio::audioThread( void *ptr )
{
     audio *play = (audio *)ptr;
     play->playAudio();
     delete play;
     return NULL;
}

void audio::playAudio(void)
{
     test = 0;
     /* playback code */
}

int audio::play(char *filename)
{
     ....
     ....
     test = 1;
     if (pthread_create( &playThread, NULL, &audio::audioThread, NULL) != 0)
     {
             return -1;
      }

     return 0;
}

The aboce program would crash when the thread function playAudio would try to write 0 to test. What's wrong? Thank you.

Recommended Answers

All 4 Replies

See the comments for explanation for the error ...

void *audio::audioThread( void *ptr )
{
[B]     // ptr is NULL here[/B]
     audio *play = (audio *)ptr;

     // now you call playAudio() through a NULL pointer 
     play->playAudio();
     delete play;
     return NULL;
}

void audio::playAudio(void)
{
     // here the 'this' pointer is NULL, hence you have no access to
     // member variables, so the seg-fault is coming up ...
     test = 0;
     /* playback code */
}

int audio::play(char *filename)
{
     test = 1;

     // Here it starts to go wrong, because you pass in 
     // NULL as argument to audio::audioThread() ...
     if (pthread_create( &playThread, NULL, &audio::audioThread, NULL) != 0)
     {
             return -1;
      }

     return 0;
}

Well, after some thinking I put the "this" pointer into function argument, so it passes the current class to the thread function, like so -

if (pthread_create( &playThread, NULL, &audio::audioThread, this) != 0)

instead of NULL. Now it works!!!
Thanks a lot for the help and explanation!!!

Well, after some thinking I put the "this" pointer into function argument, so it passes the current class to the thread function, like so -

if (pthread_create( &playThread, NULL, &audio::audioThread, this) != 0)

instead of NULL. Now it works!!!
Thanks a lot for the help and explanation!!!

Then you might want to remove the line delete play; in audio::audioThread() (if you still have it there). Or at least consider the consiquences of deleting the object inside that function i.e. once you have called audio::play() on an audio object, you are not to do anything else with that particular object instance anymore.

good point... :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.