Multi-threading

This is a discussion on Multi-threading within the Linux Programming forums, part of the Platform Specific Boards category; I created threads just fine. However, when I try to loop the main program and execute the threads and the ...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    14

    Multi-threading

    I created threads just fine. However, when I try to loop the main program and execute the threads and the functions anew all over again, the thread creation does not complete. It is weird because I don't get any error message. It just creates the first set of threads, once it is finished and tries to loop to create new threads all over again, it does not. My guess is that the threads are already created and it cannot reuse them. I called cancel thread on the cleanup section of my code, but it did not recognize the thread passed in. What am I doing wrong?

    Code:
    //------------------------ Methods ---------------------------------
    int main ( int argc, char ** args )
    {
      if ( !parseArgs(argc, args) )
        {
          fprintf(stderr,"Usage: %s -n numLoops -i userPercentage -p numLists -s queueSize\n", args[0]);
          return 1;
        }
    
    	while(numLoops>0)
    	{
    		printf("\nNUMLOO{s : %d",numLoops);
    		printf("userper: %dl",userPer);
    printf("\nnumlist: %d",numList);
    printf("\nqzises: %d", qSize);
      initialize(); // initialize variables
      generateProducerThreads();
      generateConsumerThreads();
      mainThreadWait();
          cleanup(); // free memory
      numLoops--;
    }
    
      return 0;
    }
    
    
    
    
    void mainThreadWait()
    {
      int totalItems = numCP * numList;
      int i;
    
      // continuously check if the total number of items to be produced has been
      // consumed;
      while ( true )
        {
          if ( consumedCount == totalItems )
    	{
    	  // all done, cancel all threads, exit program
    	  for ( i=0; i < numCP; i++ )
    	    {
    	      if ( pthread_cancel(bsConsIDs[i]) != 0 )
    		fprintf(stderr,"pthread_cancel failed"), exit(1);
    	    }
    
    	  printf("MAIN THREAD: All items consumed, exiting program.\n");
    	  return;
    	}
          else // sleep for a second
    	{
    	  sleep(1);
    	}
        }
    }
    
    void initialize()
    {
      initoutput(&output); //->>>>>**changed to take in ptr
      queueInit(qSize);
      Init(&MUTEX_SEM, 1);
      Init(&EMPTY_SEM, qSize);
      Init(&FULL_SEM, 0);
      Init(&ITEM_ID_MUTEX_SEM, 1);
      Init(&INCR_CONS_COUNT_SEM, 1);
        Init(&DISPLAY_FROM_UI, 1); //->>>>>>>**new init
    }
    
    
    
    void cleanup()
    {
    	Remove(MUTEX_SEM);
      Remove(EMPTY_SEM);
      Remove(FULL_SEM);
      Remove(ITEM_ID_MUTEX_SEM);
      Remove(INCR_CONS_COUNT_SEM);
      	Remove(DISPLAY_FROM_UI); //->>>>**new remove
      queueDestroy();
      free(prodIDs);
      free(bsConsIDs);
        free(userIDs); //->>>*new free
        int i;
        	  for ( i=0; i < 2; i++ )
    		    {
    				printf("\n\nI woudlbe %d\n\n",i);
    		      if ( pthread_cancel(prodIDs[i]) != 0 )
    			fprintf(stderr,"\n the new thread cancel failed"), exit(1);
    	    }
      close(output);
    }
    
    
    
    void generateProducerThreads()
    {
    	printf("\nIn producer threads\n");
      int i=0;
    
      // allocate prodIDs array
      if ( (prodIDs=malloc(numCP * sizeof(int))) == NULL )
        fprintf(stderr,"malloc failed (out of memory)\n"), exit(1);
    printf("\n\nPRIDIS: %d",prodIDs);
    
      for ( i=0; i < numCP; i++ )
        {
    		printf("\nABOUT TO craete rorpd thrd\n");
          if ( pthread_create(prodIDs+i,
    			  NULL,
    			  (void*)(&startProducer),
    			  prodIDs+i) != 0 )
    	fprintf(stderr,"pthread_create failed\n"), exit(1);
    	printf("\nFINISHE MAKING THRED\n");
        }
        printf("\nDONE IN PROD THREAD\n");
    }
    
    
    
    void generateConsumerThreads()
    {
      int i=0;
    
      // allocate bsConsIDs array
      if ( (bsConsIDs=malloc(numCP * sizeof(int))) == NULL )
        fprintf(stderr,"malloc failed (out of memory)\n"), exit(1);
        printf("\n\nCONSIDS: %d",bsConsIDs);
      for ( i=0; i < numCP; i++ )
        {
          // bubble sort consumer
          if ( pthread_create(bsConsIDs+i,
    			  NULL,
    			  (void*)(&startBubSortConsumer),
    			  bsConsIDs+i) !=0 )
    	fprintf(stderr,"pthread_create failed\n"), exit(1);
        }
    }

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,505
    Well I see
    - incomplete code
    - poorly formatted code
    - memory being used after free - track this -> free(prodIDs);
    - why is the first and last parameter to pthread_create the same?
    - why does the malloc allocate the wrong size type?
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    14

    threads

    The complete code is attached. When I free the memory, after one loop, everything starts all over again and initialize all the objects again. The first param in pthread_create is the id of the thread when I first allocate it, and the final param is the same thread id being passed into the function I am calling (&start*).
    Attached Files Attached Files

  4. #4
    Registered User
    Join Date
    Oct 2005
    Posts
    14
    Anyone??? You don't even have to look at the entire code, I just need to know if it is possible ot create multiple threads in a while loop. I enter the while loop, create the threads which they perform their tasks, and repeat as many times as the while loop requires. Is this possible?

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,505
    > The complete code is attached.
    Except for the 3 header files no doubt containing the useful information on what say P() and V() do.

    Does this even compile?
    I'm sure it generates a load of warnings.

    Here are a few things for you to worry about.
    1. Your theoutput() function does nothing to fill in the convert array before trying to output it.

    2. void initoutput(int *output)
    You also have a global variable called output - this is called shadowing - you get the parameter version rather than the global variable.

    3. if ((output = open("coutputfile"
    Surely you meant if ((*output = open("coutputfile"
    If you want to copy the returned file descriptor to your variable

    4. printf("userper: %dl", userPer);
    That's no way to print a double.
    You REALLY need to compile with
    gcc -W -Wall -ansi prog.c
    and make sure your code is warning free before even attempting to run the code.

    > sleep(1);
    This sleeps all the threads, because sleep() puts the whole process to sleep, not just the thread which calls sleep(). Use a thread primitive to make just this thread sleep, or use a thread primitive to wait for something useful to happen in another thread.

    > fprintf(stderr, "pthread_cancel failed"), exit(1);
    The use of a comma operator just to avoid braces just plain sucks.

    Code:
        for (i = 0; i < numCP; i++) {
            printf("\nABOUT TO craete rorpd thrd\n");
            if (pthread_create(prodIDs + i,
                               NULL,
                               (void *) (&startProducer), prodIDs + i) != 0)
                fprintf(stderr, "pthread_create failed\n"), exit(1);
            else
                pthread_create(prodIDs + i, NULL, (void *) (&startProducer),
                               prodIDs + i)
                    printf("\nFINISHE MAKING THRED\n");
        }
    Man, what a mess!
    1. Fix the spelling, it doesn't inspire confidence in the rest of the code if you can't get the spelling right in a simple printf statement.
    2. What's with the logic here - why have a createthread in both halves of the if()
    The one in the else isn't even valid code.

    > srand48((unsigned int) time( NULL ) );
    > srandom(time.tv_usec);
    Two different random number generators, both reseeded with disturbing regularity.
    1. Choose one
    2. seed it just ONCE in main()

    > r = (double) drand48();
    What's with the cast - the function already returns a double.

    Thread functions should be
    Code:
    void *startProducer ( void *param ) {
      int* prodId = param;
    }
    Cast the void pointer parameter into a pointer of the correct type inside the function.
    Then you can get rid of those hooky casts when you create the threads in the first place.

    Have you checked that all your sorting etc actually works without cluttering everything up with threads?
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    Registered User
    Join Date
    Oct 2005
    Posts
    14
    the sorting works, the output functions I removed, I will not output doubles, and yes my sorting does work without cluttering everything. I removed the double thread creations in the if statement as well. I only tried that because: when I loop the program again, absolutely NO threads are created. I do not know why, I have been working on this for days and I still can't find what is wrong.

  7. #7
    Registered User
    Join Date
    Oct 2005
    Posts
    14

    headers

    Forgot to post the header files....however, I know that I have no issues with these. The header files work just fine. It is when I try to loop my programin the main while loop that the threads don't recreate (after the first run).
    Attached Files Attached Files

  8. #8
    Registered User
    Join Date
    Oct 2005
    Posts
    14
    Update: I run the program once and it runs just fine. The second time it loops around, it goes into the init() function but it doesn't generate the threads at all, then it exits as if everything executed. The third time (and the last time it can loop due to the error I am trying to resolve) it loops around, it actually does generate the thread but skips the init() function altogether and it never reaches the end of the program. It is weird because I don't get a seg fault or any other kind of error message once it runs a third and last time. I say it is the last time because I try to execute it > 3 but it just gets stuck at the third run and does not execute the rest of the code. What is going on?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. overlapped I/O and multi threading
    By krishnampkkm in forum C++ Programming
    Replies: 2
    Last Post: 06-22-2009, 03:27 PM
  2. Multi Threading
    By beon in forum C Programming
    Replies: 5
    Last Post: 12-04-2006, 08:21 PM
  3. Replies: 6
    Last Post: 06-02-2006, 08:32 AM
  4. starting to learn multi threading
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 06-09-2004, 01:44 PM
  5. Multi Threading
    By IceBall in forum C Programming
    Replies: 7
    Last Post: 07-13-2003, 03:01 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21