2014-02-21 216 views
1

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

+0

您不应将'&i'传递给您的线程,它甚至可能会在您的线程访问它之前递增。绝对是一场比赛。 – HAL

+1

@HAL由于OP在'pthread_create'之后直接调用'pthread_join',所以它是安全的,因为这意味着程序基本上是单线程的。 –

+1

@JoachimPileborg当然这不会导致崩溃,但是这种传递并不是一个好习惯。 – HAL

回答

4

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

在你的情况下,如果你没有从线程函数中实际返回任何东西,那么你可以通过NULL来获得第二个参数pthread_join

+0

谢谢!但是现在pthread_self()生成相同的线程ID,是用于获取线程ID的正确方法吗? https://computing.llnl.gov/tutorials/pthreads/man/pthread_self.txt –

+2

@McKevin它可能会给你相同的线程ID,因为你的程序在所有实际中仍然是单线程的。你可以在'pthread_create'之后直接调用'pthread_join',这意味着主线程将在继续之前等待创建的线程完成。如果你想使它成为真正的多线程,那么在一个循环中创建线程,然后在另一个循环中对所有创建的线程调用'pthread_join'。但要保重,先阅读HAL的评论。此外,你应该真的有一些错误检查(以确保线程创建成功)。 –

+1

谢谢,我打破了创建并加入两个循环,现在它是多线程的。 –