Pthread_create在C ++中导致分段错误

时间:2014-02-21 08:12:59

标签: c++ pthreads coredump

我正在尝试接受Integer值,并在程序中创建该数量的线程。很奇怪,只能创建第一个线程。在进行一些跟踪之后,它会显示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循环中,它可以运行但它会给我所有相同的Thread 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

为什么Thread ID相同?

1 个答案:

答案 0 :(得分:4)

可能的原因可能是你在64位机器上,其中int是32位但指针是64位。这意味着您的pthread_join调用将在为变量status分配的空间之外写入。变量i被覆盖的可能性不大(在第二个循环中打印的地址暗示与第一个地址的差别很大)。

在您的情况下,如果您实际上没有从线程函数返回任何内容,您也可以将NULL传递给pthread_join的第二个参数。