首页 文章

Pthread_create导致C中的分段错误

提问于
浏览
1

我正在尝试接受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 回答

  • 4

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

    在你的情况下,你实际上没有从线程函数返回任何东西,你也可以传递 NULL 作为 pthread_join 的第二个参数 .

相关问题