将int转换为void *会失去精度,并且在所需的情况下解决方案是什么

时间:2016-10-09 21:54:36

标签: c++ pthreads

我知道这种错误的原因。 “int”不足以容纳“void *”的字节。但我的问题是,当我想传递一个函数的参数来执行它时,我应该如何处理Linux的pthread_create。在许多例子中,我看到了这样的函数forward-declaration:

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()执行。

1 个答案:

答案 0 :(得分:1)

你可能传递int本身而不是指向int的颜色。

你应该实际传递指针

$(function() {
  // Handler for .ready() called.
});

并在result = pthread_create(&thread_id, NULL, thread_proc, (void *)&new_request_socket); 中使用它:

thread_proc(void *arg)

编辑:澄清Sam和Lightness关于传递指针void thread_proc(void *arg) { int new_request_socket = *arg; //please put appropriate cast }

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

基本上使thread_proc成为指针,你必须编写更多代码。所以不要编写更多代码并使用new_request_socket:)

相关问题