1

Is it possible to do so?

I want to execute the following statements...

while(1){
    fputs(ch, b);
    printf("Extracting information please wait..."); //This is the line I want to execute in intervals
}

Is it possible to do so in C? I tried keeping a x variable for making the print statement execute slower like this:

while(1){
   fputs(ch, b);
   if(x%10 == 0)
      printf("...");
   x++;
}

But obviously it makes the execution of filling of the file slower. Is there any way? I know most probably there isn't because C executes line by line as it ain't a scripting language, but still. Can we use sleep() somehow for this purpose? Or is the only way is to make both the statements wait?

bayblade567
  • 270
  • 1
  • 10
  • C or C++? The answer is different for different languages, and you tagged both. – Wintermute May 14 '15 at 16:20
  • Yeah that is because I thought, even the C++ coders would be able to answer it, I want for C. – bayblade567 May 14 '15 at 16:20
  • 2
    This is a typical multithreading problem. Which means it requires a multithreading solution. Otherwise the main thread will get interrupted, slowing the program down. – laurisvr May 14 '15 at 16:21
  • 1
    It's either threads or `setitimer`, and I suspect `setitimer` is not the solution for you because there's precious little you're allowed to do in signal handlers. – Wintermute May 14 '15 at 16:22
  • I have never done multithreading in C...thanx...I will check it out..... – bayblade567 May 14 '15 at 16:23

1 Answers1

1

I've put together a sample code that I think might help you.

The code below uses a library called pthread to get the job done.

Be advised that it works on linux and I am not sure if it will work on other Operating Systems.


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

void * thread1(void* arg)
{
    while (i)
    {
        printf("Extracting information please wait...\n");
        fflush(stdout);
        sleep(1);
    }
    return (void *) 0;
}

int main(void) {

    //declaring the thread variable -- will store the thread ID
    static pthread_t pthread1;

    //creates the thread 'thread1' and assing its ID to 'pthread1'
    //you could get the return code of the function if you like
    pthread_create(&pthread1, NULL, &thread1,NULL);

    // this line will be written once and would be the place to run the command you want
    printf("You could start fgets now!! remember to put it after the creation of the thread\n");
    fflush(stdout);

    // since I am not writing anything to the file stream I am just waiting;
    sleep(10);
    return EXIT_SUCCESS;
}

Hope it helps.

Ibrahim
  • 11
  • 3