Multithreading (pthread) Interview Question -1
Write a C Program to print even numbers in one thread and odd numbers in another thread?
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
pthread_t oddThread,evenThread;
sem_t semEven,semOdd;
int counter = -1;
void *oddFn(void *arg)
{
while (counter < 15) {
sem_wait(&semOdd);
printf("Counter:%d\n",++counter);
sem_post(&semEven);
}
pthread_exit(NULL);
}
void *evenFn(void *arg)
{
while (counter < 15) {
sem_wait(&semEven);
printf("Counter:%d\n",++counter);
sem_post(&semOdd);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int ret;
sem_init(&semEven, 0, 1);
sem_init(&semOdd, 0, 0);
ret = pthread_create(&evenThread, NULL, evenFn, NULL);
if (ret != 0) {
perror("Error in creating Thread\n");
exit(1);
}
ret = pthread_create(&oddThread, NULL, oddFn, NULL);
if (ret != 0) {
perror("Error in creating Thread\n");
exit(1);
}
pthread_join(evenThread, NULL);
pthread_join(oddThread, NULL);
sem_destroy(&semEven);
sem_destroy(&semOdd);
pthread_exit(NULL);
}
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
pthread_t oddThread,evenThread;
sem_t semEven,semOdd;
int counter = -1;
void *oddFn(void *arg)
{
while (counter < 15) {
sem_wait(&semOdd);
printf("Counter:%d\n",++counter);
sem_post(&semEven);
}
pthread_exit(NULL);
}
void *evenFn(void *arg)
{
while (counter < 15) {
sem_wait(&semEven);
printf("Counter:%d\n",++counter);
sem_post(&semOdd);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int ret;
sem_init(&semEven, 0, 1);
sem_init(&semOdd, 0, 0);
ret = pthread_create(&evenThread, NULL, evenFn, NULL);
if (ret != 0) {
perror("Error in creating Thread\n");
exit(1);
}
ret = pthread_create(&oddThread, NULL, oddFn, NULL);
if (ret != 0) {
perror("Error in creating Thread\n");
exit(1);
}
pthread_join(evenThread, NULL);
pthread_join(oddThread, NULL);
sem_destroy(&semEven);
sem_destroy(&semOdd);
pthread_exit(NULL);
}
Comments
Post a Comment