我試圖接受一個整數值,並在程序中創建這個線程數。奇怪的是,只有第一個線程可以創建。經過一些跟蹤之後,它顯示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相同?
您不應將'&i'傳遞給您的線程,它甚至可能會在您的線程訪問它之前遞增。絕對是一場比賽。 – HAL
@HAL由於OP在'pthread_create'之後直接調用'pthread_join',所以它是安全的,因爲這意味着程序基本上是單線程的。 –
@JoachimPileborg當然這不會導致崩潰,但是這種傳遞並不是一個好習慣。 – HAL