Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



C Interfaces and Implementations: Techniques for Creating Reusable Software (Add    (ISBN: 0201498413)


 

 List Price: $44.99
 Our Price: $44.99
 Used Price: $28.89

 Release Date: 20 August, 1996
 Manufacturer: Addison-Wesley Pub Co (Paperback)
 Sales Rank: 48,594

 Author: David R. Hanson









More Info

 POSIX Thread Example 2003-05-28 12:52:38
 
Category: source:c:general
Description: Create multiple POSIX thread processes and wait for each one to complete.
Platform: unix
Author: detour
Viewed: 9880
Rating: 3.8/5 (73 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
pthread.c
/* pthread.c by detour@metalshell.com
 *
 * Create multiple POSIX thread processes and wait for
 * each one to complete.
 *
 * http://www.metalshell.com/
 *
 */

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <time.h>

#define NUM_THREADS 10

/* This becomes the main() of the new thread.  It
   is requred to return void * and take void * as a
   parameter. */
void *thread_function(void *arg) {
  fprintf(stdout, "Thread: %d running.\n", (int)arg);

  // Sleep for arg+1 seconds to verify pthread_join.

  sleep((int)arg+1);

  fprintf(stdout, "Thread: %d done.\n", (int)arg);

  pthread_exit(0);
}

int main() {
  int cnt;
  pthread_t p_thread[NUM_THREADS];

  for(cnt = 0; cnt < NUM_THREADS; cnt++)
    /* Returns 0 on successful creation of the thread.  The second
       parameter, left NULL for this example,  allows for options
       like CPU scheduling to be set. */
    if(pthread_create(&p_thread[cnt], NULL, thread_function, (void *)cnt) != 0)
      fprintf(stderr, "Error creating the thread");

  // Cycle through each thread and wait until it is completed.

  for(cnt = 0; cnt < NUM_THREADS; cnt++) {
    // Waits for p_thread[cnt] to finish.

    pthread_join(p_thread[cnt], NULL);
  }

  fprintf(stdout, "All threads completed.\n");

  return 0;
}
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?