Assignment 8: POSIX Threads
Implementing POSIX threads in a C program:
C function used to create POSIX threads:
#include <pthread.h>
void* start_routine(void *);
int pthread_create(pthread_t *thread, const pthread_attr_t
*attr, void *(*start_routine) (void *), void *arg);
C function used to wait for POSIX threads to end and rejoin parent
process:
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
Sample code:
void* pth_body(void *args) {
// here give the code for leap year check
printf("Thread number: %d\n", *((int *)args));
}
int main() {
pthread_t thread; // an id for a pthread
int count = 0;
while(1) {
count++;
// create a thread with pth_body as the function it
executes
pthread_create(&thread, NULL, &pth_body, &count);
//wait for the thread to terminate
pthread_join(thread, NULL);
sleep(1); // to slow down the outputs
}
}
Output: