sajal
sajal

Reputation: 91

dynamic thread creation in c++

This is my code for multi threading (This is not the actual code but parts of different files at one place where I feel I am doing something wrong)

//main function
Example ExampleObj;
for (int i=0;i<10;i++)
{
pthread_t *service_thread = new pthread_t;
pthread_create(service_thread, NULL,start,&ExampleObj);
}

//start function
void *start(void *a)
{
    Example *h = reinterpret_cast<Example *>(a);
    h->start1();
    return 0;
}


class Example
{
    public:
    void start1()
    {
    std::cout <<"I am here \n";
    }
};

Code is not giving any error but it's not coming to start1 function as well. Please let me know if I am creating the threads correctly or not. If not, then what is the correct way.

Upvotes: 0

Views: 1852

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

There is no code that stops your main() from terminating the process before your worker threads have completed.

main() should look something like:

int main() {
    Example ExampleObj;

    // Start threads.
    pthread_t threads[10];
    for(size_t i = 0; i < sizeof threads / sizeof *threads; ++i) {
        pthread_create(threads + i, NULL,start,&ExampleObj);
    }

    // Wait for the threads to terminate.
    for(size_t i = 0; i < sizeof threads / sizeof *threads; ++i) {
        pthread_join(threads[i], NULL);
    }
}

Upvotes: 1

Related Questions