4

Parallel execution

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <pthread.h>
  5.  
  6. #define NLOOPS      1000
  7.  
  8. void *fping( void *np ) {
  9.     int i, j;
  10.  
  11.     for ( i = 0; i < NLOOPS; i++ ) {
  12.         printf( "ping." );
  13.         for ( j = 0; j < 1000; j++ )
  14.             (void) rand();
  15.     }
  16.     pthread_exit( 0 );
  17. }
  18.  
  19. void *fpong( void *np ) {
  20.     int i, j;
  21.  
  22.     for ( i = 0; i < NLOOPS; i++ ) {
  23.         printf( "pong." );
  24.         for ( j = 0; j < 1000; j++ )
  25.             (void) rand();
  26.     }
  27.     pthread_exit( 0 );
  28. }
  29.  
  30. int main( int argc, char *argv[] ) {
  31.     pthread_t ping, pong;
  32.  
  33.     pthread_create( &ping, 0, fping, 0 );
  34.     pthread_create( &pong, 0, fpong, 0 );
  35.  
  36.     pthread_exit( 0 );
  37. }
$ gcc -Wall -lpthread pingpong.c -o pingpong
$ ./pingpong
ping.ping.pong.ping.pong.ping.pong.ping.ping.pong.ping.pong.pong...

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].