从int到void*的转换是可能的

conversion from int to void * is possible?

本文关键字:转换 int void      更新时间:2023-10-16

我正在学习多线程概念http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm.我遇到了这个疑问。。在下面的示例程序中,他正试图将int转换为void。。我认为将int转换为void是非法的,int地址应该转换为void。。

我提到代码belw,请看一下。

示例1:-

 #include <iostream>
 #include <cstdlib>
 #include <pthread.h>
 using namespace std;
 #define NUM_THREADS     5
 void *PrintHello(void *threadid)
{
  long tid;
 tid = (long)threadid;
 cout << "Hello World! Thread ID, " << tid << endl;
 pthread_exit(NULL);
}
  int main ()
 {
   pthread_t threads[NUM_THREADS];
    int rc;
    int i;
    for( i=0; i < NUM_THREADS; i++ ){
     cout << "main() : creating thread, " << i << endl;
     rc = pthread_create(&threads[i], NULL, 
                      PrintHello, (void *)i);//this was the line where he is converting int to void *,i feel this is correct (void *)&i but result is not as expected if i change it
     if (rc){
       cout << "Error:unable to create thread," << rc << endl;
       exit(-1);
    }
  }
  pthread_exit(NULL);
  }

示例2:-

#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS     5
 struct thread_data{
 int  thread_id;
 char *message;
};
  void *PrintHello(void *threadarg)
 {
    struct thread_data *my_data;
     my_data = (struct thread_data *) threadarg;
   cout << "Thread ID : " << my_data->thread_id ;
   cout << " Message : " << my_data->message << endl;
   pthread_exit(NULL);
}
  int main ()
  {
    pthread_t threads[NUM_THREADS];
    struct thread_data td[NUM_THREADS];
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){
     cout <<"main() : creating thread, " << i << endl;
  td[i].thread_id = i;
  td[i].message = "This is message";
  rc = pthread_create(&threads[i], NULL,
                      PrintHello, (void *)&td[i]);//in this he is typecasting by thread_data address to void *
  if (rc){
     cout << "Error:unable to create thread," << rc << endl;
     exit(-1);
  }
 }
   pthread_exit(NULL);
   }

你能解释一下为什么他没有将int地址变量类型转换为void*的区别吗

您是对的,通常它可能不起作用,因为我们对intvoid*的相对大小几乎没有保证。然而,在成功实现pthread的系统上,void*将足够大以容纳int

这样做的原因是pthread_create的接口获取void*,并在启动时将其传递给线程函数。这个想法可能是这个参数应该是指向某个数据结构的指针。然而(再次(,当数据小到int时,您可以欺骗并直接传递它。

请注意,PrintHello函数会立即将参数强制转换回其原始类型(必须达成一致(。

此外,您不必将数据指针强制转换为void*,因为这种转换是隐式的。不过,您必须使用强制转换才能恢复原始类型。