Skip to content

Instantly share code, notes, and snippets.

@baileylo
Created December 20, 2012 22:33
Show Gist options
  • Save baileylo/4349158 to your computer and use it in GitHub Desktop.
Save baileylo/4349158 to your computer and use it in GitHub Desktop.
//Brian McBride
//Ping Pong application
//9/15/08
#include <pthread.h>
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int displayType = 0;
int pairs = 0;
pthread_cond_t conditionPing = PTHREAD_COND_INITIALIZER;
pthread_cond_t conditionPong = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *ping ( void *){
int i;
for( i = 1; i <= pairs; i++){
pthread_mutex_lock( &mutex );
while( displayType != 0 )
pthread_cond_wait( &conditionPing, &mutex);
displayType = 1;
std::cout<< i << ".) Ping\n";
pthread_cond_signal( &conditionPong );
pthread_mutex_unlock( &mutex );
}
pthread_exit(0);
}
void *pong ( void *){
int i;
for( i = 1; i <= pairs; i++){
pthread_mutex_lock( &mutex );
while( displayType != 1 )
pthread_cond_wait( &conditionPong, &mutex);
displayType = 0;
if( i < 10 ){
std::cout<<" Pong\n\n";
}else
std::cout<<" Pong\n\n";
pthread_cond_signal( &conditionPing );
pthread_mutex_unlock( &mutex );
}
pthread_exit(0);
}
int main(int argc, char * argv[]){
pairs = atoi(argv[1]);
pthread_t tID[2];
pthread_create( tID, NULL, ping, NULL);
pthread_create( tID + 1, NULL, pong, NULL);
pthread_exit( NULL );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment