Problem 1: Write a program that accepts an integer N as a command line input and
ID: 3910656 • Letter: P
Question
Problem 1: Write a program that accepts an integer N as a command line input and then proceeds to launch N threads within that process. Each thread should consist of an infinite loop that prints out "Thread k running" (once every second) where k is a thread index (from 0 to N-1). After 5 seconds of running, your main program should kill thread 0, then after another 5 seconds, should kill thread 1, and so on until all threads have been terminated. At that time, your main program should itself terminate. Hints: In Windows, you can use the function CreateThread to launch a new thread. In Unix/Linux, you can use the pthread library. There is great documentation online for both (thank you Google).Explanation / Answer
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include<pthread.h>
#include<errno.h>
#include <stdlib.h>
#include <signal.h>
void *myThreadFun(void *vargp)
{
int *p = (int *)vargp;
while(1){
sleep(1);
printf(" Thread %d running ",*p);
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t *tid;
tid = (pthread_t *)malloc(sizeof(pthread_t) * atoi(argv[1]));
int *count = (int *) malloc(sizeof(int) * atoi(argv[1]));
int i;
for (i = 0; i<atoi(argv[1]); i++){
count[i] = i;
}
//pthread_create(&tid[0], NULL, myThreadFun, &i);
//pthread_create(&tid[1], NULL, myThreadFun, &j);
for (i = 0; i<atoi(argv[1]); i++){
pthread_create(&tid[i], NULL, myThreadFun, &count[i]);
}
for (i = 0; i<atoi(argv[1]); i++){
sleep(5);
printf("Killing %d thread ",i);
pthread_cancel(tid[i]);
}
//sleep(5);
//pthread_cancel(tid[0]);
//pthread_join(tid, NULL);
//printf("After Thread ");
exit(0);
}