C ++,为一个返回类型的函数创建一个pthread? [英] C++, create a pthread for a function with a return type?

查看:130
本文介绍了C ++,为一个返回类型的函数创建一个pthread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下函数:

  bool foo(int a); //此方法声明不能更改。 

如何创建一个pthread?我怎么知道函数返回了什么?我在网上看,似乎任何函数,我想创建一个pthread必须以 void * 作为参数,必须返回 void * 以及,我不太确定如何铸造所有这一切将工作,或在哪里我会得到返回的布尔。



我是C ++新手,请随身携带=)

解决方案>

只要你只处理bools(实际上是整数),有可能将函数转换为pthread函数类型,因为指针与(一些)整数是兼容的类型:

  pthread_t pid; 
pthread_create(& pid,NULL,(void *(*)(void *))foo,(void *)argument)但是,你最好将函数包装到另一个与pthread兼容的函数中,然后返回一个指针,然后返回一个指针。到它的返回值(使用后必须是free()'d):

  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);

使用这种方法,以后你可以调用任意返回或参数类型。


Say I have the following function:

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

How do I create a pthread for this? And how do I find out what the function returned? I've looked online and it seems like any function I want to create a pthread for must take a void* as an argument, and must return void* as well, and I'm not quite sure how the casting for all this would work, or where I would get the returned bool.

I'm new to C++, so please bear with me =)

解决方案

As far as you're dealing only with bools (which are, in fact, integers) it's possible, however not recommended, to cast the function to a pthread function type, as a pointer is compatible with (some) integer types:

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

However, you'd better wrap your function into another, pthread-compatible one, then return a pointer to its return value (must be free()'d after use):

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

then use:

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

With this method, in the future you'll be able to call a function with arbitrary return or argument types.

这篇关于C ++,为一个返回类型的函数创建一个pthread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆