Skip to content

Instantly share code, notes, and snippets.

@alherd-by
Created April 14, 2016 12:20
Show Gist options
  • Save alherd-by/e693090bfdaa069f11542e7b032ca633 to your computer and use it in GitHub Desktop.
Save alherd-by/e693090bfdaa069f11542e7b032ca633 to your computer and use it in GitHub Desktop.
#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