creating pthreads runtime

  • Follow


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?
0
Reply a.k.vora (41) 9/23/2008 2:02:16 AM

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

new pthread_t()

i missed "_t"

Happy Programming :)
0
Reply a.k.vora (41) 9/23/2008 2:32:53 AM


Neel wrote:
> 
> 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.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.
0
Reply cbfalconer (19183) 9/23/2008 5:06:33 AM

Neel <a.k.vora@gmail.com> writes:
> I 'm facing some prob with creating pthreads.
[...]

Try asking in comp.programming.threads.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21549) 9/23/2008 6:55:36 AM

On 23 Sep 2008 at  2:32, Neel wrote:
> On On 23 Sep 2008 at  2:02, Neel wrote:
> > if(threadCounter<5){
> >   pthread_create(new pthread(), NULL, handleConnection, NULL);
> > }
> 
> 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.

0
Reply nospam59 (9950) 9/28/2008 3:42:17 PM

4 Replies
37 Views

(page loaded in 0.086 seconds)


Reply: