Aditya Jha
Aditya Jha

Reputation: 69

Sleep() in a Thread in c

I want my program to print

So I have written the below code. Whats actually happening is

How to correct it ?

Whats actually happening is i

void *myThreadFun(void *vargp)
{
    while (1)
    {
        sleep(1);
        printf("hello");
    }
}

Upvotes: 0

Views: 3541

Answers (2)

dlmeetei
dlmeetei

Reputation: 10391

Try this, You need to flush the stream which can be either done by fflush or by adding \n.

printf does not always call write for performance reason as system calls are costly. It rather buffers it and write at once when required. By adding, \n or fflush make the buffer to be printed on stdout everytime.

void *myThreadFun(void *vargp)
{
    while(1){
        printf("hello\n");
        sleep(1);
    }
}

Upvotes: 6

user2371524
user2371524

Reputation:

C stdio is buffered with three different modes supported:

  • unbuffered: everything is read or written directly
  • line buffered: data is held in the buffer until it's full or a newline is encountered
  • full buffered: data is held in the buffer until it's full

You can always force a buffer flush with fflush(). So, adding fflush(stdout) after your printf() will work.

As stdout is by default in line buffered mode, you can also just append \n (a newline) to your string, the newline will trigger a buffer flush.

Upvotes: 3

Related Questions