在`C``线程池`中运行`POSIX`线程内运行`功能指针`

时间:2013-03-26 14:13:58

标签: c posix threadpool

我正在使用pthreads在C中创建一个线程池,虽然我知道它是如何工作的,但我还是有一些关于错综复杂的问题。

我创建了一个结构,它应该是我对线程池的表示,包含要运行的函数指针列表,我们称之为work_list。线程池结构还包含互斥访问的互斥(?)和条件,线程数的int和包含每个工作线程的线程ID的数组.work_list本身包含表示要完成的函数的结构,每个实例都包含结构包含一个函数的void *,一个用于args的void *和一个用于放置结果的void *。在编码时,这个想法就像这样充实:

typedef struct threadpool
{
    list work_list;
    pthread_t* tidArray;
    int num_threads;
    pthread_mutex_t lock;
    pthread_cond_t condition;
} threadpool;

typedef struct fuFunction
{
    void* functionCall;
    void* functionArgs;
    void* returnValue;
    list_elem elem;
} fuFunction;

我目前有一个初始化池的线程。它接受一个int num_of_threads,并返回一个指向线程池实例的指针,其中所有成员都已初始化。我创建的身体看起来像这样:

threadpool * threadpool_init(int num_of_threads)
{
    threadpool* retPool = (threadpool*) malloc(sizeof(threadpool));

    //Initialize retPool members

    int x;
    for(x = 0; x < num_of_threads; x++)
    {
            pthread_t tid;

            if( pthread_create(&tid, NULL, thread_start, retPool) != 0)
            {
                    printf("Error creating worker thread\nExting\n");
                    exit(1);
            }

            retPool->tidArray[x] = tid;
    }

    return retPool;
}

启动时每个线程运行的函数,worker函数thread_star,到目前为止看起来像这样:

void *thread_start(void* args)
{
    threadpool* argue = (threadpool*) args;

    pthread_mutex_lock(&(argue->lock));
    while(\* threadpool not shut down*\)
    {
            if(!list_empty(&argue->work_list))
            {
                    fuFunction* tempFu = list_entry(list_pop_front(&argue->workQ), fuFunction, elem);

                    \\WHAT TO PUT HERE
            }

            pthread_cond_wait(&argue->condition, &argue->lock);
    }
    pthread_mutex_unlock(&(argue->lock));
}

我的问题是,假设我目前拥有的代码是正确的,我如何让工作线程在其在worker函数中生成的tempFu中运行该函数?对不起,如果这很长或令人困惑,我发现在谈话中更容易解释。如果这是FUBAR,请告诉我。

1 个答案:

答案 0 :(得分:0)

struct element signiture“void * functionCall;”是错的。 改为使用函数指针。 例如:

typedef struct fuFunction
{
    void* (*functionCall)( void* arg);
    void* functionArgs;
    void* returnValue;
    list_elem elem;
} fuFunction;

然后放在那里:

tempfu->returnValue = (*tempfu->functionCall)(tempfu->functionArgs);