【发布时间】:2014-02-21 08:12:58
【问题描述】:
我正在尝试接受一个整数值,并在程序中创建该数量的线程。奇怪的是,只能创建第一个线程。经过一些跟踪,它显示 pthread_create 是导致核心转储的行。
#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 join 的第二个参数更改为 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 因为 OP 在
pthread_create之后直接调用pthread_join,所以它是安全的,因为这意味着程序基本上是单线程的。 -
@JoachimPileborg 当然这不会导致崩溃,但是这个参数传递肯定不是一个好习惯。
-
有什么理由不使用C++ threads?与原始 pthread API 不同,它们是类型安全的。
-
@McKevin Pass
i。有关将参数传递给线程的更多信息,computing.llnl.gov/tutorials/pthreads/#PassingArguments