【问题标题】:Casting int to void* loses precision, and what is the solution in required cases将 int 转换为 void* 会失去精度,在需要的情况下解决方案是什么
【发布时间】:2017-02-18 07:46:47
【问题描述】:

我知道这个错误的原因。 “int”不够大,无法容纳“void *”的字节。但我的问题是,当我想传递函数的参数以使其执行时,我应该如何处理 Linux 的pthread_create。在许多示例中,我看到了这样的函数前向声明:

void* thread_proc(void* arg);

然后在函数中,一个文件指针作为arg(它的类型为int)传递。但是编译器(逻辑上)会抛出一个错误,警告不要将 int 强制转换为 void。我什至使用过 intptr_t(又名长指针)但无济于事。

result = pthread_create(&thread_id, NULL, thread_proc, (void *)new_request_socket);

new_request_socket 是一个表示套接字 fd 的 int。

我如何将整数作为函数的参数传递,它本身作为函数传递给pthread_create()

【问题讨论】:

  • 你不需要处理pthread_create。您只需使用std::thread。问题解决了。
  • 将指针传递给int 而不是直接传递int 值。
  • @SamVarshavchik 你能详细说明一下吗?
  • 有什么要详细说明的? “使用std::thread 并避免整个问题”的哪一部分不清楚?

标签: c++ pthreads


【解决方案1】:

您可能传递的是 int 本身而不是指向 int 的指针。

你实际上应该传递指针

result = pthread_create(&thread_id, NULL, thread_proc, (void *)&new_request_socket);

thread_proc(void *arg) 中使用它:

void thread_proc(void *arg)
{
    int  new_request_socket = *arg; //please put appropriate cast
}

编辑:澄清 Sam 和 Lightness 关于传递指针 thread_proc 的要点:

  • 不要将指针传递给局部变量,即应该使用 malloc 在堆上分配 new_request_socket
  • 应使用锁简化对new_request_socket 的同时访问
  • thread_proc 阅读之前不要免费new_request_socket

基本上将new_request_socket 设为指针,您将不得不编写更多代码。所以不要写更多代码并使用std::thread :)

【讨论】:

  • 这不太可能是安全的,除非您进行进一步的修改。
  • 这种方法的问题是new_request_socket 需要保持在范围内,直到新线程读取它。
  • @LightnessRacesinOrbit 是的,但这是 pthread_create 的限制,它接受指针,因此您的程序必须设计为处理这些情况。
  • 是的,但它应该被设计为正确处理它们。当然,自 2000 年代初以来,(通常)没有充分的理由使用这种古老的类似 C 的废话。 boost::thread 现在是 std::thread plzkthx。
猜你喜欢
  • 2010-12-11
  • 2019-10-23
  • 1970-01-01
  • 2022-12-31
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
相关资源
最近更新 更多