2017-04-23 18 views
1

これは私の問題です。例えば、私のプログラムには、常に動作する必要がある操作Aがあります(1秒間に15回呼び出される関数のように)。操作Aは大量のデータを収集します。その後、ユーザーはこの大きなデータをファイルにエクスポートします。この操作B(すなわち、ファイルへのデータのエクスポート)は、操作Aが停止しないようにバックグラウンドで実行されるべきである。Cでバックグラウンド処理を実行する最善の方法

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

それともこれを行うための別の方法があります:

は、私はこのようなpthreadsを使用してバックグラウンド化を実行することはできますか?

+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(); 
} 
関連する問題