【问题标题】:conversion from int to void * is possible?从 int 到 void * 的转换是可能的吗?
【发布时间】:2015-08-21 10:55:50
【问题描述】:

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

我提到了下面的代码,请看一下。

示例 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 *

【问题讨论】:

    标签: c++ linux multithreading


    【解决方案1】:

    你说得对,一般来说它可能不起作用,因为我们几乎不能保证intvoid* 的相对大小。但是,在成功实现 pthread 的系统上,void* 将大到足以容纳 int

    这样做的原因是 pthread_create 的接口采用void* 并在启动时将其传递给线程函数。这个想法很可能是这个参数应该是指向某个数据结构的指针。但是(再次),当数据小到 int 时,可以作弊直接传过去。

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

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

    【讨论】:

    • 还要注意第二个例子是不正确的。 main 函数退出并让其他线程继续运行,并且仍然能够访问在 main 中本地声明的现在不存在的 thread_data。要更正它,您需要在 main 之外声明数据,或者您应该在 main 中加入线程,直到所有线程都完成。
    猜你喜欢
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2016-06-06
    • 1970-01-01
    相关资源
    最近更新 更多