C ++,为具有返回类型的函数创建pthread?

时间:2012-01-26 21:32:28

标签: c++ pthreads posix

说我有以下功能:

bool foo (int a); // This method declaration can not be changed.

如何为此创建pthread?我如何找出函数返回的内容?我看过网上看起来像我想要创建pthread的任何函数必须以void*作为参数,并且必须返回void*,我不太确定铸造所有这些都可行,或者我会得到返回的布尔。

我是C ++的新手,所以请耐心等待我=)

4 个答案:

答案 0 :(得分:5)

至于你只处理bools(实际上是整数),有可能(但不推荐)将函数转换为pthread函数类型,因为指针与(某些)整数类型兼容:

pthread_t pid;
pthread_create(&pid, NULL, (void *(*)(void *))foo, (void *)argument));

但是,你最好将你的函数包装到另一个与pthread兼容的函数中,然后返回一个指向它的返回值的指针(使用后必须是free()):

void *foo_wrapper(void *arg)
{
    int a = *(int *)arg;
    bool retval = foo(a);
    bool *ret = malloc(sizeof(bool));
    *ret = retval;
    return ret;
}

然后使用:

pthread_t pid;
pthread_create(&pid, NULL, foo_wrapper, &a);

使用此方法,将来您将能够使用任意返回或参数类型调用函数。

答案 1 :(得分:1)

您可以在函数对象中封装要调用的函数,然后在pthread函数中调用该函数对象:

首先,定义一个封装函数调用的函数对象。

struct foo_functor {
    // Construct the object with your parameters
    foo_functor(int a) : ret_(), a_(a) {}

    // Invoke your function, capturing any return values.
    void operator()() {
        ret_ = foo(a_);
    }

    // Access the return value.
    bool result() {
        return ret_;
    }

private:
    bool ret_;
    int a_;
};

其次,使用适当的pthread签名定义一个函数,该签名将调用你的函数对象。

// The wrapper function to call from pthread. This will in turn call 
extern "C" {
    void* thread_func(void* arg) {
        foo_functor* f = reinterpret_cast<foo_functor*>(arg);
        (*f)();
        return 0;
    }
}

最后,实例化您的函数对象,并将其作为参数传递给thread_func函数。

foo_functor func(10);

pthread_t pid;
pthread_create(&pid, NULL, thread_func, &func);
pthread_join(pid, NULL);

bool ret = func.result();

答案 2 :(得分:0)

一个简单的解决方法是使用void * foo(int a,bool&amp; b)。

答案 3 :(得分:0)

bool在功能上等同于int。 false(通常)为0,true为其他任何内容。因此

void *foo(void *a){
  int *a_int = (int *)a;
  //do things
  bool *x = new bool;
  *x = answer; 
  pthread_exit(x);
}

然后在你的主要部分,你会得到返回的结果,然后将其重新投入布尔。

bool *x; 
pthread_join(thread,(void *)x);
//Answer is *x