Q: pthread sync problem

From: Erik Larsson (erik_at_ortogonal.com)
Date: 03/30/04


Date: 30 Mar 2004 11:56:48 -0800

I have a small server in C/C++, every time a new connection the main
program spawns a new thread that handles the client (lets call it
client-thread). That thread also spawns 10-30 other threads that do
some information gathering (lets call them workers). So the
‘client-thread' does something like this to synchronize all
‘workers-threads':

pthread_t *tid = new pthread_t[num_threads];
...
for(int i=0; i<num_threads; i++)
   {
       pthread_create(&tid[i], &attr, workerThread, param);
   }

for(int i=0; i<num_threads; i++)
   {
       pthread_join(&tid[i], NULL);
   }
...
delete[] tid;

I have two questions:
1 – When many connections arrives something happens with the
‘tid'-array, some pointers screws up and that results in a
segmentation fault. I know that this is a bad thing to do, to use new
in threads. But how shall I solve that? TSD?

2 – Is it possible to synchronize the ‘workers-threads' without using
pthread_join? My problem is that the first workers-thread finishes
after 5 sec and the second workers-thread finish after just 2 sec.
Would it be possible to solve this so that the client-thread can do
something else during the time that al others workers-thread shall be
finished.

Thanks for any advice /Erik