繁体   English   中英

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

[英]Pthread_create causing segmentation fault in C++

我试图接受一个I​​nteger值,并在程序中创建该数量的线程。 奇怪的是,只能创建第一个线程。 进行一些跟踪之后,它表明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];的声明pthread_t threads[threadsNumb]; 进入for循环,它可以运行,但是会给我所有相同的线程ID,这是不希望的。 任何想法可能是核心转储的原因吗? 解决这个小问题花了我几个小时。 我也研究了类似的问题,但是我没有重新声明任何内容: pthread_create导致分段错误

这是将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相同?

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

在您实际上没有从线程函数返回任何内容的情况下,您最好为pthread_join的第二个参数传递NULL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM