C++的异步函数调用

idd*_*dqd 6 c c++ asynchronous

我需要一个提示如何在C/C++中实现异步函数调用(或者用于windows和/或linux的框架/ API调用的名称)

用例如下:父线程调用函数.该函数创建一个子线程并返回,因此调用是非阻塞的,父线程可以继续做一些工作.

例如,获取结果的pthread_join不合适,因此必须将结果存储在堆中,并且必须通知父级.我想要的是像父线程中的回调函数,它将在子线程准备好作业后执行.

这是令人惊讶的,但我在谷歌找不到一个例子.

感谢帮助

Mat*_*ner 8

C++ 0x提供std::async了这个.这是现有的实现,讨论维基百科.


ale*_*cov 7

pthread_join()您可以使用POSIX C实现所需的效果,而不是使用不同的框架,并注意到您在问题中提到的内容.为此,您可以使用信号来确认并行任务完成的线程.在此方法中,您为用户定义的信号(SIGUSR1例如)安装信号处理程序,创建一组具有不同任务的工作线程,并让它们在完成时发出父信号.

以下程序说明了这种尝试.在示例中,我用于SIGUSR1通知父线程完成某些处理.父线程一直忙着做一些I/O,直到子线程中断为止.请注意,为清楚起见,没有放置任何类型的错误处理代码.

#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/* Variable to hold the value of some calculation. */
int value = 0;

/* Variable used by the parent thread to inform itself of task completion. */
volatile sig_atomic_t value_received = 0;

/* Signal handler to handle the SIGUSR1 signal (the signal used to acknowledge the parent of task completion). */
void handler(int signum) {
    value_received = 1;
}

/* Working thread routine. First parameter is a pthread_t (cast to void*) identifying the parent. */
void *thread(void *parent) {
    /* Do something lengthy here, such as a long calculation. */
    value = 1;
    sleep(5); /* Simulate lengthy operation. */

    /* After processing, inform the parent thread that we have ended. */
    pthread_kill((pthread_t)parent, SIGUSR1);
    return NULL;
}

int main(void) {
    struct sigaction action;
    pthread_t child;

    /* Install signal handler to receive the child thread notification. */
    action.sa_handler = handler;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    sigaction(SIGUSR1, &action, NULL);

    /* Create child thread that will perform some task. */
    pthread_create(&child, NULL, thread, (void*)pthread_self());

    /* Detach thread from execution. No need to join the thread later. */
    pthread_detach(child);

    /* Do some other processing while the ongoing task is running in parallel. */
    while (!value_received) {
        char buffer[0x100];

        /* Echo some input until something happens. */
        if (!fgets(buffer, sizeof buffer, stdin))
            break;
        printf("You typed: %s", buffer);
    }

    /* Something happened (signal received or EOF in stdin). In the latter, just sleep a little while. */
    if (feof(stdin))
        while (!value_received)
            sleep(1);

    /* At this point, child thread has already ended the execution. */
    printf("Value received: %i\n", value);
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

该示例使用LinuxThreads信号实现,这与POSIX定义的完全不同.如果您担心可移植性或合规性,则应进一步修改上述解决方案.


Jon*_*erg 3

增强线程

我相信这可以很好地完成工作。将函数调用作为一个新线程启动,并且不必费心加入它。无论如何,我相信当它完成时它会解决这个问题。

您可以进行设置,以便子级在使用Boost.Signals完成后向父级发送信号。该信号将链接到父级的回调函数。