首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >多线程程序中的核心转储: basic_string::_S_construct null无效

多线程程序中的核心转储: basic_string::_S_construct null无效
EN

Stack Overflow用户
提问于 2013-05-03 22:24:05
回答 1查看 1.5K关注 0票数 0

我希望4个线程将进入同一个名为read的函数中,并执行该函数中的操作(读取,然后在显示器上打印,并显示所有内容...)。问题是:

代码语言:javascript
运行
复制
terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid
trAborted (core dumped)

代码是:

代码语言:javascript
运行
复制
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;

struct v {
    int id;
    char* ad;

    v(int a, char* t) {
        id = a;
        ad = t;
    }
};

int bank = 1000;
pthread_mutex_t mutex;

void* read(void* argument)
{
    cout << "tr";
    v* d;
    int num;
    d = (v*) argument;
    string l = d->ad;
    int n = d->id;
    string x = "";
    ifstream textfile;
    textfile.open(l.c_str());
    while (!textfile.eof()) {
        textfile >> x;
        if (x == "SUB") {
            pthread_mutex_lock(&mutex);
            textfile >> num;
            bank = bank - num;
            cout << "person num " << n << " sub " << num << " dollars and know in the Bank: " << bank << endl;
            pthread_mutex_unlock(&mutex);
        }
        if (x == "ADD") {
            pthread_mutex_lock(&mutex);
            textfile >> num;
            bank = bank + num;
            cout << "person num " << n << " add " << num << " dollars and know in the Bank: " << bank << endl;
            pthread_mutex_unlock(&mutex);
        }
        if (x == "GET") {
            pthread_mutex_lock(&mutex);
            cout << "person num " << n << " look in the Bank: " << bank << endl;
            pthread_mutex_unlock(&mutex);
        }


    }
    textfile.close();
    return 0;
}

int main(void)
{
    pthread_mutex_init(&mutex, NULL);
    int i = 0, j = 0;
    v data1(1, "file1.dat"), data2(2, "file2.dat"), data3(3, "file3.dat"), data4(4, "file4.dat");
    pthread_t t1, t2, t3, t4;
    i = pthread_create(&t1, NULL, read, (void*)&data1);
    if (i != 0) cout << "error" ;
    j = pthread_create(&t2, NULL, read, (void*)&data2);
    if (j != 0) cout << "error" ;
    i = pthread_create(&t3, NULL, read, (void*)&data3);
    if (i != 0) cout << "error" ;
    j = pthread_create(&t4, NULL, read, (void*)&data4);
    if (j != 0) cout << "error" ;

    pthread_exit(NULL);

    return 0;
}
EN

Stack Overflow用户

回答已采纳

发布于 2013-05-04 01:50:32

您将线程数据传递到堆栈上,这几乎不是一个好主意。

调用pthread_exit时,将释放包含dataN对象的主线程堆栈。如果你的一个线程在pthread_exit之后被调度,它将对释放的对象进行操作。

最好的解决方案是通过new在堆上分配data对象。

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16361210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档