2010-11-26 71 views

回答

5

什麼? t是一個線程,它並不真正「看到」任何東西。嚴格來說,它是一個代表一個線程的變量 - 你實際上沒有創建線程 - 但假設你創建了一個線程,它運行在與main()相同的進程中,所以它在這個意義上共享內存空間,但它不會「分享主要的範圍。在該線程中運行的函數可以看到這些函數的範圍內的變量。

您可以將指針傳遞給i作爲指向pthread_create的用戶數據指針。或者,如果您需要訪問的不僅僅是i,您可以將指針傳遞給某個包含(除其他之外)指向i的結構的指針,依此類推。

示例代碼:

#include <pthread.h> 
#include <iostream> 
#include <cstring> 

void *thread_entry_point(void *data) { 
    int *idata = static_cast<int*>(data); 
    std::cout << "thread: i = " << *idata << "\n"; 
    *idata = 23; 
    return const_cast<char*>("might as well return something"); 
} 

int main() { 
    int i = 12; 
    pthread_t thr; 

    int err = pthread_create(&thr, 0, thread_entry_point, &i); 
    if (err == 0) { 
     void *result; 
     pthread_join(thr, &result); 

     std::cout << "main: result = " << static_cast<const char*>(result) << "\n"; 
     std::cout << "main: i = " << i << "\n"; 
    } else { 
     std::cout << "error creating thread: " << err << " " << std::strerror(err) << "\n"; 
    } 
} 
+0

那麼......你可以將`&i`作爲參數傳遞給線程,將它放入線程函數的作用域。 – 2010-11-26 01:06:34

3

並行線程不是特殊。例如,下面的代碼有同樣的「問題」:

void foo() 
{ 
    i = 5; 
} 
int main() 
{ 
    int i; 
    foo(); 
} 

當然foo被稱爲main,所以他們即使是在同一個線程。然而foo沒有在main中看到int。解決方法很簡單:如果foo需要一個intmain應該傳遞:

void foo(int& i) 
{ 
    i = 5; 
} 
int main() 
{ 
    int i; 
    foo(i); 
} 

隨着線程,情況是一樣的:通過你需要共享的內容。