我试图接受一个整数值,并在程序中创建这个线程数。奇怪的是,只有第一个线程可以创建。经过一些跟踪之后,它显示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