-2
我正在學習的多線程概念。 我在下面的示例程序,他正試圖轉換INT到void * .. 我認爲INT轉換到void *是違法的,INT地址應轉換爲void * ..碰到過這樣的doubt..here從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 *
另請注意,第二個示例不正確。主函數退出並保持其他線程在運行,並且仍然能夠訪問在main中本地聲明的現在不存在的thread_data。要糾正它,你需要在main之外聲明數據,或者你應該在main中加入這些線程,直到所有的線程都完成爲止。 –