【问题标题】:Running `Function Pointers` Within Running `POSIX` Thread in `C` `Thread Pool`在“C”“线程池”中运行“POSIX”线程中运行“函数指针”
【发布时间】:2013-03-16 09:03:59
【问题描述】:

我正在使用 pthreads 在 C 创建一个线程池,虽然我知道它是如何工作的,但我对其中的复杂性有一些疑问。

我创建了一个结构,它应该是我的线程池表示,包含要运行的函数指针列表,我们将其称为 work_list。 threadpool 结构还包含互斥锁(?)和同步访问的条件,线程数的 int 和保存每个工作线程的线程 id 的数组。 work_list 本身包含表示要完成的函数的结构,这些函数的每个实例structs 为函数保存一个 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;
}

每个线程在启动时运行的函数,工作函数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));
}

我的问题是,假设我目前拥有的这段代码是正确的,我将如何让工作线程运行它在工作函数中创建的 tempFu 中的函数?抱歉,如果这很长或令人困惑,我发现这在对话中更容易解释。如果这是 FUBAR,也请告诉我。

【问题讨论】:

    标签: c posix threadpool


    【解决方案1】:

    结构元素签名“void* functionCall;”是错的。 改用函数指针。 例如:

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

    然后放在那里:

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

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 2015-03-08
      • 2012-12-23
      • 1970-01-01
      相关资源
      最近更新 更多