0

我希望 4 个线程进入同一个名为的函数read并执行函数中的操作(读取,之后在监视器上打印,并全部显示......)。问题:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid
trAborted (core dumped)

代码是:

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

1 回答 1

2

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

当您调用 时,将释放pthread_exit包含对象的主线程堆栈。dataN如果您的某个线程在 之后被安排pthread_exit,它将对已释放的对象进行操作。

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

于 2013-05-03T17:50:32.037 回答