我正在实现一种算法,其中我使用了CPP的线程库和用于MultiCore的英特尔TBB库。虽然我在线程的帮助下调用函数有时它执行完美,有时它会给运行时异常。我正在尝试找到原因但找不到。请找到提供例外的代码段示例。
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <tbb/pipeline.h>
#include <tbb/atomic.h>
#include <tbb/concurrent_queue.h>
#include <tbb/compat/thread>
#include <tbb/tbbmalloc_proxy.h>
using namespace std;
using namespace tbb;
#define pi 3.141593
#define FILTER_LEN 265
class MyBuffer
{
public:
double *acc;
double *buffer;
int start,end;
MyBuffer()
{
start=0;
end=0;
buffer=new double[150264];
acc=new double[150000];
fill_n(buffer,150264,0);
}
~MyBuffer()
{
delete[] buffer;
delete[] acc;
}
int startnumber()
{
return start;
}
int endnumber()
{
return end;
}
};
typedef concurrent_queue<MyBuffer> QueueMyBufferType;
QueueMyBufferType chunk_queue;
atomic<bool> stop_flag;
// input function that will be running by thread to generate sinewave
void input_function()
{
stop_flag = false;
cout<<"thread reached to call input function " <<endl;
ofstream o("testing sinewave.csv");
int counter=0;
while(counter<150000)
{
cout<<"value of counter is \t" <<counter << endl;
//MyBuffer *b=new MyBuffer;
MyBuffer b;
b.start=(FILTER_LEN-1+(counter));
b.end=(25264+(counter));
cout<<"value of b.start is and b.end is "<<b.start<<"\t" <<b.end<<endl;
for(int i =b.startnumber(); i <b.endnumber(); i++)
{
b.buffer[i] = sin(700 * (2 * pi) * (i / 5000.0));
o<<b.buffer[i]<<endl;
}
chunk_queue.push(b);
cout<<"object pushed in queue and value of j is \t" <<counter <<endl;
counter+=25000;
}
stop_flag = true;
cout<<"all data is perfectly generated" <<endl;
}
int main()
{
thread input_thread(input_function);
while(!stop_flag)
{
//cout<<"waiting for thread " << endl;
}
cout << "\n All Data is processed \n\n" << endl;
return 0;
}
此代码是应用程序的一部分,有助于生成正弦波。请帮助找出我出错的地方。
答案 0 :(得分:1)
在:
b.end=(25264+(MyBuffer::j));
25264+(MyBuffer::j)
可能会超出成员数组buffer
绑定检查MyBuffer::j<150000
可能是MyBuffer::j<150000-25264
while(counter<150000-25264)
{ ... }