creating pthreads runtime

N

Neel

Hi,
I 'm facing some prob with creating pthreads.
My requirement is to create threads in a loop.
but I dont want to make an array of pthread.

At anytime I want to have 5 threads (I used a global variable as a
counter).
Whenever the counter is less than 5, I want to create new thread.

whenever any thread is about to terminate, I will decrement the
counter. (of course avoiding race conditions using mutex lock).

But 'm confused how to create thread at run time.

I tried something like


pthread_mutex_lock(&check_thread_count);

if(threadCounter<5){
pthread_create(new pthread(), NULL, handleConnection, NULL);
}

pthread_mutex_unlock(&check_thread_count);

using *new pthread()* is not correct.

So how can I create pthread at run time?
 
N

Neel

sorry friends,
I made syntax error there...
I got the solution..
It should be

new pthread_t()

i missed "_t"

Happy Programming :)
 
C

CBFalconer

Neel said:
I'm facing some prob with creating pthreads.
My requirement is to create threads in a loop.
but I dont want to make an array of pthread.
.... snip ...

using *new pthread()* is not correct.

So how can I create pthread at run time?

There are no pthreads in the C language. Thus this is off-topic.
 
A

Antoninus Twink

I got the solution..
It should be

new pthread_t()

i missed "_t"

This is a recipe for a memory leak. As you never keep track of the
pthread_t * you get from new (an operator which incidentally is only
available in C++, not in vanilla C), you'll have no way of freeing the
memory with delete once the thread exits.

You should either have a pthread_t variable and pass its address to
pthread_create(), or else keep a record of the pointer from new,
use pthread_join() somewhere appropriate and make sure to delete/free()
the memory used by the pthread_t structure.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top