c - 在 C 中执行背景的最佳方式

标签 c pthreads background-process

这是我的问题。例如,我的程序中有一个操作 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/

相关文章:

c - 使用 union 变量分配两个值

c - Vulkan:vk*CreateInfo 结构中的 sType 有什么意义?

c - 如何将文件中的字符放入字符串中?

java - Android 蓝牙搜索服务中可用设备

c - 如何以标准方式修剪前导/尾随空格?

c++ - 了解段错误情况下的 gdb 输出

c - pthread_join() 期间的段错误

c - pthread线程池场景

ios - 在后台使用 NSURLSession 一个一个地下载 100 个文件的列表

ios - 如何在 iOS 8 中应用程序处于后台状态时连续执行任务