Thread: Creating pthreads in for loop

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    3

    Creating pthreads in for loop

    Hi all,

    I'm encountering a little problem creating a variable amount of pthreads.
    I tried to create this threads in a loop, but that will give me a segmentation fault...

    Salem explained here why, but there isn't a solution for me in that topic.

    Is there a way to create a number of threads in a for loop?

    I was trying it this way, but as said before, that gives a segmentation fault.

    Code:
    void* function(int nmbr){
        int i;
        pthread_t threads[nmbr];
    
        for(i=0;i<nmbr;i++){
            pthread_create(&threads[i], NULL,function2,(void *)i);
            pthread_join(thread[i],NULL);     
        }
    return NULL;
    }

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,974
    I don't really see anythying wrong with what you've posted - other than not checking return values.

    Let's see function2().

    gg

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    i do not see a reason to create thread and suspend the calling thread till created thread exits - you can just call the function2 in a loop with the same effect

    so what is your intentions?

    and also - could you show the function2 code - I'm interested how you read the parameters
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  4. #4
    Registered User
    Join Date
    Feb 2008
    Posts
    3
    Thanks codeplug for the quick reply.

    It is a big bummer There was u huge seg fault in function2

    Thanks for paying my attention to it.

    But Salem is wrong in his post than?

  5. #5
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,974
    Salem is correct. That code used "&i" and you are using "(void*)i".

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. using pthreads with an API that uses pthreads
    By MK27 in forum C Programming
    Replies: 3
    Last Post: 03-06-2009, 02:47 PM
  2. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  3. Pthreads performance
    By C_ntua in forum C Programming
    Replies: 42
    Last Post: 06-17-2008, 11:29 AM
  4. Creating A Thread W/ PThreads within an Object
    By HalNineThousand in forum Linux Programming
    Replies: 12
    Last Post: 03-28-2008, 02:57 PM
  5. pthreads and resources
    By ubermensch in forum C Programming
    Replies: 2
    Last Post: 02-07-2006, 02:27 AM