stellarossa
stellarossa

Reputation: 1800

pthread_create does nothing when called from a wrapper function

I'm trying to implement a threaded object like this:

#include <pthread.h>
#include <iostream>

class Thread
{
private:
    int id;
    static void * run(void * arg)
    {
        int tid = (int)arg;
        std::cout << "Thread " << tid << " executed." <<std::endl;
        pthread_exit(NULL);
    }
public: 
    Thread(int _id);
    void start();
    int get_id();
};

Here's the implementation of the public methods & constructor:

#include "std_thread.h"

Thread::Thread(int _id)
{
    id = _id;
}

void Thread::start()
{
    std::cout << "Thread created." <<std::endl;
    pthread_t thread;
    int rc = pthread_create(&thread, NULL, run, (void*)id);
    if(rc) 
        std::cout << "Return code from thread is " << rc;
}

int Thread::get_id()
{
    return id;
}

And here's main:

#include "std_thread.h"

int main()
{
    Thread *thd = new Thread(0);
    thd->start();

    return 0;
}

When I create the thread object and call its start method, which is in turn supposed to print "Thread created." and run the thread body - it doesn't; actually, it does print Thread created to console, but doesn't seem to create a thread, or the thread just doesn't do anything. Everything compiles fine by the way, and there no run time errors.

Any ideas?

Upvotes: 0

Views: 992

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

Your main returns before the thread gets a chance to run.

The program doesn't wait until all threads are done before exiting - once main is over, it's over, and the process is just shut down.

Have your pthread_t thread; as a member instead of a local variable, and add a method to wait for the thread to finish.
This is the simplest example I can come up with:

void Thread::wait()
{
    pthread_join(thread, NULL);
}

int main()
{
    Thread thd(0); // There's no point in using dynamic allocation here.
    thd.start();
    thd.wait();
    return 0;
}

Upvotes: 1

Related Questions