Thread: create multiple threads dynamically

  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    2

    create multiple threads dynamically

    hello

    I have a client-server program in which I need to accept connections of multiple clients and create a thread to serve each one of them.
    I don't know from before the number of the threads that have to be created so for every connection I have to allocate space.
    Here's what I do

    Code:
    pthread_t *tids;
    thread_counter=0;
    
    if (( tids = new pthread_t (sizeof ( pthread_t )) ) == NULL ) 
      exit(1);
    if(thread_counter!=0){    
        tids+1=new pthread_t (sizeof ( pthread_t ));
        tids=tids+1;
    
        if(tids==NULL)
            cout<<"error with realloc"<<endl;*/
    }
            
    if(err=pthread_create(tids,NULL,parse,(void*)argument))        
    {
        perror("pthread create\n");
        exit(1);
    }
    
    thread_counter++;
    The above is in a while loop and allocates space for the first thread and then creates it.
    For every new connection it allocates space for a new thread(thread_counter>0) and creates it.
    The problem seems to appear with the pthread_create for the second thread etc.
    (The program is compiled with g++ and that's why new is used,but vectors are not allowed so the rest of the program is in C)

  2. #2
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    If you're trying to dynamically re-allocate the array of thread, it's not correct. You need array brackets with new to show that it is an array, and you never free memory.

    Also, spawning a new thread for every client is very wasteful when select or poll could get the job done with only one thread.

  3. #3
    Registered User
    Join Date
    Jul 2012
    Posts
    2
    Code:
    if(thread_counter!=0)
    {	
    	tids =(pthread_t*)realloc(tids,sizeof ( pthread_t )*(thread_counter+1)) ;
    	if(tids==NULL)
    	cout<<"error with realloc"<<endl;
    }
    you mean something like that will not work?
    I did't quite understand what you mean with brackets.
    Could you give me an example?
    thank you

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Why not just use a std::vector?
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    Quote Originally Posted by CornedBee View Post
    Why not just use a std::vector?
    Quote Originally Posted by www View Post
    but vectors are not allowed so the rest of the program is in C
    That's why. Also

    Code:
    tids+1=newpthread_t (sizeof( pthread_t ));
    Don't you mean
    Code:
    tids+sizeof(pthread_t)=newpthread_t (sizeof( pthread_t ));
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by www
    The program is compiled with g++ and that's why new is used,but vectors are not allowed so the rest of the program is in C
    Why are vectors not allowed? Why compile with g++ and use new when the rest of the program is in C?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    you could also try a doubly linked list. no need to re-allocate whole arrays of things. just one thing at a time, and insert/remove/append/prepend operations are computationally very cheap.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    FWIW, if you're making this much of a meal of allocating memory to store a few thread handles, you're nowhere near ready for the complexities that threaded code will present you.

    Do as memcpy suggested in post #2 and just use a single thread with select. It's a bit of extra effort to get it to work properly, but you'll keep your sanity trying to debug it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    the trouble with using a single thread only is that any long running request will block all other clients until it is finished. my preferred solution to this is to use select/poll to find connections that are waiting for some sort of processing, and spin each request off into its own thread.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    How so?

    Use select() to watch all the open file descriptors.
    Use a timeout with select() so it doesn't block if there is no traffic at all.
    For each active descriptor, perform a single read() to get available data, and pass that onto the corresponding handling function.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by Salem View Post
    For each active descriptor, perform a single read() to get available data, and pass that onto the corresponding handling function.
    but if that handler takes a long time to return, you don't get back to the next call to select until it's done, causing all other connections to be potentially unresponsive. spawning the handler in a thread allows it to complete asynchronously, and (nearly) immediately returns to the main loop that calls select.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Create array of pointers dynamically
    By sombrancelha in forum C Programming
    Replies: 15
    Last Post: 04-03-2011, 02:54 AM
  2. Dynamically create an array?
    By Unknowntoyou000 in forum C++ Programming
    Replies: 16
    Last Post: 04-25-2008, 03:49 PM
  3. Can I dynamically create vectors of multiple depths?
    By 6tr6tr in forum C++ Programming
    Replies: 8
    Last Post: 04-14-2008, 02:47 AM
  4. Dynamically create Identifiers?
    By mcrewry in forum C Programming
    Replies: 1
    Last Post: 12-28-2006, 12:22 PM
  5. a point of threads to create multiple threads
    By v3dant in forum C Programming
    Replies: 3
    Last Post: 10-06-2004, 09:48 AM