4

A simple thread of execution

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <pthread.h>
  5.  
  6. #include <errno.h>
  7. #include <string.h>
  8.  
  9. #define NTHREADS    5
  10.  
  11. void *hello( void *tnump ) {
  12.     printf( "Hello World #%d!\n", *(int *) tnump );
  13.     pthread_exit( 0 );
  14. }
  15.  
  16. int main( int argc, char *argv[] ) {
  17.     pthread_t threads[NTHREADS];
  18.  
  19.     int rc, tnum;
  20.  
  21.     for ( tnum = 0; tnum < NTHREADS; tnum++ ) {
  22.         printf( "Creating thread #%d\n", tnum );
  23.         rc = pthread_create( &threads[tnum], 0, hello, (void *) &tnum );
  24.         if ( rc )
  25.             fprintf( stderr, "%s\n", strerror( errno ) );
  26.     }
  27.     pthread_exit( 0 );
  28. }
$ gcc -Wall -lpthread hello.c -o hello
$ ./hello
Creating thread #0
Creating thread #1
Hello World #1!
Creating thread #2
Hello World #2!
Creating thread #3
Hello World #3!
Creating thread #4
Hello World #5!
Hello World #4!

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].