2015-08-21 29 views
-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 *

回答

2

你是正確的, 一般它可能不起作用,因爲我們幾乎沒有關於int和的相對大小的保證。但是,在成功實現pthread的系統上,void*將足夠容納int

這樣做的原因是pthread_create的接口,它需要void*並在啓動時將其傳遞給線程函數。這個想法很可能是這個參數應該是一個指向某個數據結構的指針。然而(再次),當數據和int一樣小時,你可以直接作弊並傳遞它。

請注意,PrintHello函數會立即將該參數轉換回其原始類型(必須商定)。

另外,您不必將數據指針投射到void*,因爲該轉換是隱式的。你不得不使用一個強制類型來獲取原始類型。

+0

另請注意,第二個示例不正確。主函數退出並保持其他線程在運行,並且仍然能夠訪問在main中本地聲明的現在不存在的thread_data。要糾正它,你需要在main之外聲明數據,或者你應該在main中加入這些線程,直到所有的線程都完成爲止。 –

相關問題