这是我的问题。例如,我的程序中有一个操作 A 需要一直工作(就像一个每秒被调用 15 次的函数)。操作 A 收集大量数据。然后用户触发将这个大数据导出到文件。此操作 B(即导出数据到文件)应在后台执行,以便操作 A 不会停止。
我可以像这样使用 pthreads 来执行后台处理吗:
#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;
}
或者有其他方法吗?
最佳答案
通过使用 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();
}
关于c - 在 C 中执行背景的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43573267/