# Printing infinite loop using pthread [closed]

I'm trying to implement a c program using pthreads which prints "1 2 3 4 5" in an infinite loop. I have used conditional variables and mutex to synchronize the pthreads. I'm able to print "1 2 3 4 5" without race condition using conditional variables and mutexes. But the problem occurs when I try to make it an infinite loop. Can anyone please review my code and suggest the edits I have to make Inorder to get an ouptut like

1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 ...

Below is the code which I have tried implementing.

#include <stdio.h>
#include <stdlib.h>

static int count=0, count2=0, count3=0, count4=0,count5=1;

void *func1(void *a){
while(1){
while(count5 == 0){
}
printf("1 ");
count = 1;
count5 = 0;
}
}

void *func2(void *b){
while(1){
while(count == 0){
}
printf("2 ");
count2 = 1;
}
}

void *func3(void *c){
while(1){
while(count2 == 0){
}
printf("3 ");
count3 = 1;
}
}

void *func4(void *d){
while(1){
while(count3 == 0){
}
printf("4 ");
count4 = 1;
}
}

void *func5(void *e){
while(1){
while(count4 == 0){
}
printf("5 ");
count=0;
count2=0;
count3=0;
count4=0;
count5=1;
}
}

int main(int argc, char **argv){

for(int i=0; i<5; i++)

return 0;
}

• what does the posted code output? Why the loop calling pthread_join()? why the calls to pthread_cond_destroy()? why the call to pthread_mutex_destroy()? Suggest each thread near the bottom of the loop, call pthread_cond_signal() for the NEXT thread. Suggest elimination of the count# variables as they are just cluttering the code – user3629249 Sep 8 '16 at 16:37
• for ease of understanding and readability, consistenly indent the code. indent after every opening brace '{'. unindent before every closing brace '}'. – user3629249 Sep 8 '16 at 16:40
• Can anyone please mention why this question has been put on hold? Now I'm not able to answer my own question as I have got the correct output. – Vishnu N K Sep 9 '16 at 9:03

the following code does not start the output successfully every time, for which I'm not sure of the reason.

I'll let you debug that detail.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // sleep()

void *func1(void *a)
{
(void)a;

while(1)
{

printf("1 ");

}
}

void *func2(void *b)
{
(void)b;

while(1)
{

printf("2 ");

}
}

void *func3(void *c)
{
(void)c;

while(1)
{

printf("3 ");

}
}

void *func4(void *d)
{
(void)d;

while(1)
{

printf("4 ");

}
}

void *func5(void *e)
{
(void)e;

while(1)
{

printf("5 ");

}
}

int main( void )
{