-
-
Save alherd-by/e693090bfdaa069f11542e7b032ca633 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#define NUM_THREADS 10 | |
void *PrintHello(void *threadid) { | |
long tid; | |
tid = (long) threadid; | |
while (1) { | |
printf("Thread #%ld!\n", tid); | |
sleep(2); | |
} | |
} | |
int main(int argc, char *argv[]) { | |
pthread_t threads[NUM_THREADS]; | |
int rc, currentThreadCount; | |
long t; | |
char c; | |
currentThreadCount = 0; | |
while (c != 'q') { | |
switch (c = getchar()) { | |
case '=': { | |
if (currentThreadCount < NUM_THREADS) { | |
currentThreadCount++; | |
printf("Creating thread %ld\n", currentThreadCount); | |
rc = pthread_create(&threads[currentThreadCount], NULL, PrintHello, (void *) currentThreadCount); | |
if (rc) { | |
printf("ERROR; return code from pthread_create() is %d\n", rc); | |
exit(-1); | |
} | |
} else { | |
printf("Maximum number of thread reached\n"); | |
} | |
break; | |
} | |
case '-': { | |
printf("Killing thread %ld\n", currentThreadCount); | |
pthread_cancel(threads[currentThreadCount]); | |
currentThreadCount--; | |
break; | |
} | |
case 'q': { | |
exit(0); | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment