lock上的核心转储

lock上的核心转储

我正在尝试模拟一个多线程环境,每个线程都调用Kevin类的Speak函数。但是,在pthread_mutex_lock函数中(之后/期间)存在段错误,我找不到原因。 pthread_mutex_lock之后的行将永远不会执行。有人说这可能是pthread_mutex_t的声明问题,但是我在include语句之后将其全局声明。
编辑:它使用gcc版本4.1.2在redhat linux 64位上运行

#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;


pthread_mutex_t mutexsum;

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<<"before lock"<<endl;
        pthread_mutex_lock (&mutexsum);
    cout << "Name: Kevin" << *((int*)value) << "\n" << "Seconds since epoch:" << "\nThread id:" << pthread_self() << endl;
        pthread_mutex_unlock (&mutexsum);
}

int main (int argc, char *argv[])
{
cout << "HI1" << endl;
int threadsNumb = atoi(argv[1]);
pthread_t callThd[threadsNumb];
long i;
void *status;
pthread_attr_t attr;

/* Assign storage and initialize values */


pthread_mutex_init(&mutexsum, NULL);

cout << "HI2" << endl;
/* Create threads to perform the dotproduct  */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

cout << "HI3" << endl;
for(i=0;i<threadsNumb;i++)
  {
cout << "HI4" << endl;
   pthread_create(&callThd[i], &attr, Kevin::Speak, (void *)i);
   }

   cout <<"HI6"<<endl;
pthread_attr_destroy(&attr);
/* Wait on the other threads */

   cout <<"HI7"<<endl;
for(i=0;i<threadsNumb;i++) {

    cout <<"HI8"<<endl;
    pthread_join(callThd[i], NULL);

    cout <<"HI9"<<endl;
  }

pthread_mutex_destroy(&mutexsum);
pthread_exit(NULL);
}


示例输出带有第一个参数(线程号)8:

$ ./a.out 8
HI1
HI2
HI3
HI4
HI4
HI4
HI4
HI4
HI4
HI4
HI4
before lock
before lock
before lockbefore lock
before lock
before lock
Segmentation fault (core dumped)
$ ./a.out 8
HI1
HI2
HI3
HI4
HI4
HI4
HI4
HI4
HI4
HI4
HI4
HI6
HI7
HI8
before lock
Segmentation fault (core dumped)

最佳答案

这不是互斥锁调用,而是之后的提示。您引用该值时,就好像它实际上是一个长指针一样。尝试以下更改:

void* Kevin::Speak(void* value)
{
    long i = (long) value; // cast from pointer to long
    cout<<"before lock"<<endl;
    pthread_mutex_lock (&mutexsum);
    cout << "Name: Kevin" << i << "\n" << "Seconds since epoch:" << "\nThread id:" << pthread_self() << endl;
    pthread_mutex_unlock (&mutexsum);
}

关于c++ - pthread_mutex_lock上的核心转储,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21977875/

10-10 23:22