如何向clone()调用的函数传递参数?
我必须在主函数中使用clone()系统调用来获取2个线程。 (我知道,还有其他选项,但在这种情况下,它必须是clone())。
系统调用工作并且两个线程都到达指定的函数(foo)。但在这个函数中,我需要它们调用具有此签名的另一个函数:(
void increment(int* a, int b)
旁注:它将 b * 1 添加到 a。(= a+b))
重要的是,a 和 b 都在 main 中声明-function,我不知道如何将它们传递给 foo.
我已经尝试过不同的事情,但没有成功。我得到了提示:使用适配器。 但我不知道该怎么做。 (我也不知道如何在带有 int 的克隆中使用参数。)
有什么建议吗?
I have to use the clone() system call in the main-function to get 2 threads. (I know, there are other options, but in this case, it has to be clone()).
The system call works and both threads arrive in the designated function (foo). But in this function I need them to call another function with this signature:
void increment(int* a, int b)
(Sidenote: It adds b * 1 to a. (= a+b))
The important thing is, that both, a and b, are declared in the main-function and I don't know how to pass them to foo.
I already tried different things, but without success. I've gotten a hint: Use an adapter.
But I have no clue how to do this. (I also dont know how to use the args in clone with int.)
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
clone()
的参数之一是void* arg
。这允许您将 void 指针传递给您的函数。为了传递 int 指针和 int,您必须创建一个结构体,其中包含 int 指针和 int 分别分配给a
和b
,然后将指针转换为该结构体转换为 void 指针。然后在函数内反转该过程。我的 C 有点生疏,我还没有编译这个,所以不要引用我的内容,但它应该看起来大致像这样:
注意:当
fn< 时,请注意您创建的结构仍在范围内/code> 被调用,因为它没有被复制。您可能必须
malloc
它。One of the arguments to
clone()
is avoid* arg
. This lets you pass a void pointer to your function. In order to pass an int pointer and an int instead, you have to create a struct with an int pointer and int assigned toa
andb
respectively, then cast a pointer to that struct into a void pointer. Then inside the function you reverse the process.My C is a little rusty and I haven't compiled this, so don't quote me on it, but it should look roughly like this:
Note: take care that the struct you create is still in scope when
fn
is called, as it isn't copied. You might have tomalloc
it.这是示例代码:
Here is the example code: