2014-02-21 63 views
1

我試圖接受一個整數值,並在程序中創建這個線程數。奇怪的是,只有第一個線程可以創建。經過一些跟蹤之後,它顯示pthread_create是導致核心轉儲的行。Pthread_create在C++中導致段錯誤

#include <iostream> 
#include <time.h> 
#include <pthread.h> 
using namespace std; 

class Kevin 
{ 
public: 
    Kevin(); 
    static void* Speak(void* value); 
}; 

Kevin::Kevin() 
{ 
    cout << "new instance of Kevin is created\n"; 
} 

void* Kevin::Speak(void* value) 
{ 
    cout << "Name: Kevin" << *((int*)value) << "\n" << "Seconds since epoch:" << "\nThread id:" << pthread_self() << endl; 
} 

int main(int argc, char *argv[]) 
{ 
    int threadsNumb = atoi(argv[1]); 
    cout << "number of threads :" << threadsNumb <<endl; 
    int status; 
    int i; 
    pthread_t threads[threadsNumb]; 
    for(i=0;i<threadsNumb;i++) 
    { 
     cout << "what is i? " << i << endl; 
     cout << &threads[i] << i << endl; 
     cout << "threads" << threads[i] << endl; 
     cout << "thread Numb" << threadsNumb << endl; 

     pthread_create(&(threads[i]),NULL,Kevin::Speak,(void *)&i); // this line 
     pthread_join(threads[i], (void **)&status); 
     cout << endl; 
    } 
    return EXIT_SUCCESS; 
} 

用」 ./a.out 3" 運行給出的輸出:

number of threads :3 
what is i? 0 
0x7fff3600ae400 
threads6296496 
thread Numb3 
Name: Kevin0 
Seconds since epoch: 
Thread id:1117690176 

what is i? 1 
0x7fff000000081 
Segmentation fault (core dumped) 

我試過的pthread_t threads[threadsNumb];申報遷入for循環,它可以運行,但它會帶給我所有相同的線程ID,這是不需要的。任何想法可能是核心轉儲的原因?解決這個小問題需要幾個小時。 我也看了一個類似的問題,但我沒有重申任何東西:pthread_create causing segmentation fault

這是我將pthread連接的第二個參數更改爲NULL後得到的。

what is i? 0 
0x7fffe23e12f00 
threads6296496 
thread Numb3 
Name: Kevin0 
Seconds since epoch: 
Thread id:1098664256 

what is i? 1 
0x7fffe23e12f81 
threads242525729787 
thread Numb3 
Name: Kevin1 
Seconds since epoch: 
Thread id:1098664256 

what is i? 2 
0x7fffe23e13002 
threads47489276644304 
thread Numb3 
Name: Kevin2 
Seconds since epoch: 
Thread id:1098664256 

爲什麼線程ID相同?

+0

您不應將'&i'傳遞給您的線程,它甚至可能會在您的線程訪問它之前遞增。絕對是一場比賽。 – HAL

+1

@HAL由於OP在'pthread_create'之後直接調用'pthread_join',所以它是安全的,因爲這意味着程序基本上是單線程的。 –

+1

@JoachimPileborg當然這不會導致崩潰,但是這種傳遞並不是一個好習慣。 – HAL

回答

4

一個可能的原因可能是您在64位機器上,其中int是32位,但指針是64位。這意味着您的pthread_join調用將寫入分配給變量status的空間之外。變量i不會被覆蓋(由第二個循環打印的地址與第一個地址不同)。

在你的情況下,如果你沒有從線程函數中實際返回任何東西,那麼你可以通過NULL來獲得第二個參數pthread_join

+0

謝謝!但是現在pthread_self()生成相同的線程ID,是用於獲取線程ID的正確方法嗎? https://computing.llnl.gov/tutorials/pthreads/man/pthread_self.txt –

+2

@McKevin它可能會給你相同的線程ID,因爲你的程序在所有實際中仍然是單線程的。你可以在'pthread_create'之後直接調用'pthread_join',這意味着主線程將在繼續之前等待創建的線程完成。如果你想使它成爲真正的多線程,那麼在一個循環中創建線程,然後在另一個循環中對所有創建的線程調用'pthread_join'。但要保重,先閱讀HAL的評論。此外,你應該真的有一些錯誤檢查(以確保線程創建成功)。 –

+1

謝謝,我打破了創建並加入兩個循環,現在它是多線程的。 –