2017-04-23 49 views
1

這是我的問題。例如,我在我的程序中有一個操作A,它需要一直工作(就像一個被稱爲每秒15次的函數)。操作A收集大量數據。然後用戶觸發器將這些大數據導出到文件。該操作B(即將數據導出到文件)應該在後臺執行,以便操作A不停止。在C中執行背景的最佳方法

我可以執行backgrounding使用並行線程這樣的:

#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; 
} 

或者有另一種方式做到這一點?

+0

你也可以在後臺創建一個新的進程來完成這項工作。 – Shiping

+0

使用叉子時,我應該關心什麼問題?例如,當父進程死了的時候子進程結束了嗎? – PeMaCN

+0

在你的主線程中,使用'pthread_join(thread,NULL)'等待你的工作線程完成,而不是在返回調用之前的'pthread_exit(NULL)'。 – Scab

回答

1

通過使用fork()方法,你真的可以做到這一點。我只是給你一個模板,從這裏你可以繼續前進。閱讀我提供的評論。

#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(); 
}