NutCracker
NutCracker

Reputation: 12273

Best way to perform backgrounding in C

This is my problem. For example, I have an operation A in my program which needs to work all the time (like a function which is being called 15 times per second). Operation A collects large amount of data. Then user triggers exporting this large data to file. This operation B (i.e. exporting data to file) should be performed in background so that operation A does not stop.

Can I perform backgrounding by using pthreads like this:

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

void *threada() {
    int i = 0;
    for(i = 0;i < 1000;i++) {
        printf("This is new thread!\n");
    }

    pthread_exit(NULL);
}

int main() {
    int i = 0;
    pthread_t thread;
    for(i = 0;i < 105;i++) {
        printf("This is current thread!\n");
        if(i == 100) {
            pthread_create(&thread, NULL, threada, NULL);
        }
    }

    pthread_exit(NULL);
    return 0;
}

Or is there another way to do this?

Upvotes: 1

Views: 110

Answers (1)

SRIDHARAN
SRIDHARAN

Reputation: 1222

By using fork() method you can really do this. I am just giving you a template, from here you can move on. Read the comments I have provided.

#include<unistd.h>
#include <stdio.h>
#include <time.h>
clock_t begin;
clock_t end;
int a[1000],i=0;
void B(int a[],int n)
{
    printf("%d",a[0]); //do your process here.
}
void A()
{
    scanf("%d",&a[i]);
    int p;
    i++;
    end=clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    if(time_spent>=15)
    {
        p=fork();
        if(p==0) // child process will execute
        {
            B(a,i);
        }
        else //parent resets the clock
        { 
            begin=clock();
        }
    }
    A(); // This reads infinitely better write base condition to stop.
}
int main()
{

    A();
}

Upvotes: 1

Related Questions