Last active
July 3, 2016 03:20
-
-
Save amanuel2/0933b04464c0bb44089b638fd24ca219 to your computer and use it in GitHub Desktop.
Concurent Ping-Pong Example C<P-THREADS>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include<stdlib.h> | |
//64 BITS -ALL 32 bit Arch | |
//32 BIT - UNIX 64 bit arch | |
//64 BIT - WINDOWS 64 bit arch | |
long long sum = 0; | |
static enum turn | |
{ | |
PING, | |
PONG | |
}def; | |
void* sum_runner(void* arg) | |
{ | |
long long* limit_ptr = (long long *) arg; | |
long long limit = *limit_ptr;//Derefrencing | |
for(long long i=0; i<=limit; i++) | |
sum += i; | |
printf("Sum is %lld \n", sum); | |
pthread_exit(0); | |
} | |
void ping() | |
{ | |
puts("Ping"); | |
def = PONG; | |
} | |
void pong() | |
{ | |
puts("Pong"); | |
def = PING; | |
} | |
int main(int argc, char **argv) | |
{ | |
if(argc<2) | |
{ | |
puts("Usage ./objFile <num>"); | |
exit(1); | |
} | |
long long limit = atoll(argv[1]); | |
def = PING; | |
pthread_t t_id; | |
pthread_attr_t attr; | |
pthread_attr_init(&attr); | |
pthread_create(&t_id,&attr,sum_runner,&limit); | |
//Main Functions | |
for(int i=0; i<= 10; i++) | |
{ | |
if(def == PING) | |
ping(); | |
else if(def == PONG) | |
pong(); | |
else | |
puts("UNKOWN PI-PO"); | |
} | |
pthread_join(t_id,NULL); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment