Question

I'm trying to accept an Integer value, and create that number of threads in a program. Bizarre enough, only the first thread can be created. After some tracing, it shows that pthread_create is the line that causes core dump.

#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;
}

Running with "./a.out 3" gives the output of:

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)

I tried moving the declaration of pthread_t threads[threadsNumb]; into the for loop, it can run but it will gives me all same Thread id, which is not desired. Any idea what might be the cause of core dump? It's taken me hours to resolve just this one minor issue. I've also looked into a similar question but I did not re-declare anything: pthread_create causing segmentation fault

This is what I get after changing the 2nd argument of pthread join to 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

Why is the Thread id same?

Was it helpful?

Solution

A possible reason may be that you're on a 64-bit machine, where int is 32 bits but pointers are 64 bits. That means your pthread_join call will write outside the space allocated for the variable status. It's not unlikely that the variable i is overwritten (hinted to by the address you print in the second loop is so different from the first address).

In your case, where you don't actually return anything from the thread function, you might as well pass NULL for the second argument of pthread_join.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top