我使用了两个类:一个数据处理器,它将处理文件并计算每行中该字的实例总数。 尝试使用多线程来执行此操作,其中将启动线程以在每一行中处理搜索。
存储向量中每一行的计数。
在没有多线程的情况下执行时,它可以正常运行。
void DataProcessor::countInstance ()
{
int pos = -1, count = 0;
string lineFromFile;
cout << "In countInstance" <<endl;
getline (m_file, lineFromFile); <<<< Not getting line read from file
while(true)
{
pos = lineFromFile.find(mStr_word, ++pos);
if (pos != std::string::npos)
count++;
else
break;
}
mVec_countPerLine.push_back(count);
cout <<mStr_word << "****" <<lineFromFile <<endl;
cout << mVec_countPerLine[0]<<endl;
}
DataProcessor::~DataProcessor()
{
m_file.close();
}
////////
void *ThreadFunction (void *dp)
{
pthread_mutex_lock( &mutex1 );
DataProcessor *dProcessor = static_cast<DataProcessor *> (dp); <<<just curious if casting is creating a problem
cout << "IN ThreadFunction"<< endl;
dProcessor->countInstance ();
pthread_mutex_unlock( &mutex1 );
}
class MyThread
{
private:
pthread_t threads[10];
public:
MyThread ();
void createThread (DataProcessor *);
~MyThread ();
};
这里我在循环中创建线程
void MyThread::createThread (DataProcessor *dProcessor)
{
cout << "IN CREATE THREAD::";
int numLinesInFile, rc;
numLinesInFile = dProcessor->getNumLinesInFile();
for ( int i =0; i < numLinesInFile; i++)
{
rc = pthread_create(&threads[i], NULL,
ThreadFunction, (void *)&dProcessor);
if (rc)
{
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
for ( int i =0; i < numLinesInFile; i++)
pthread_join(threads[i], NULL);
pthread_exit(NULL);
}
MyThread::~MyThread ()
{
}
########################################################
Calling these two objects from:-
dProcessor.openFile("example.txt");
dProcessor.setWord(readData);
MyThread thread;
thread.createThread (&dProcessor);
dProcessor.displayResult();
但是得到:
IN CREATE THREAD::IN ThreadFunction
In countInstance
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Aborted (core dumped)
任何人都可以帮我找出原因吗?
答案 0 :(得分:0)
您的演员表示该参数是指向DataProcessor
的指针:
static_cast<DataProcessor *> (dp);
但是您将指针传递给指向DataProcessor
的指针:
(void *)&dProcessor
失去演员阵容和&符号:
rc = pthread_create(&threads[i], NULL, ThreadFunction, dProcessor);
顺便说一下:你永远不需要将指针投射到void*
。