Problems while using threading with arguments - multithreading

I have been trying to get this working for a while and I am not very skilled at C++/CLI. I am trying to loop through a 2d array and when it contains certain number create a thread to run but I keep getting errors while compiling.
Here is the thread creation:
if (map[x][y] == 8)
{
Pos^ p = gcnew Pos(x, y, map);
Thread^ t = gcnew Thread(gcnew ParameterizedThreadStart(p, &Pos::moverX));
t->Start(p);
}
else if (map[x][y] == 9)
{
Pos^ p = gcnew Pos(x, y, map);
Thread^ t = gcnew Thread(gcnew ParameterizedThreadStart(p, &Pos::moverY));
t->Start(p);
}
Here is the Pos class:
public ref class Pos
{
public:
static int px, py;
static int ** mapa;
Pos(int x, int y, int ** map)
{
px = x;
py = y;
mapa = map;
}
int getX(){ return px; }
int getY(){ return py; }
int** getMap(){ return mapa; }
static void moverX(Pos p)
{
int dy = 1;
while (true)
{
if (mapa[p.getX()+dy][p.getY()] == 1){ dy *= -1; }
Console::BackgroundColor = ConsoleColor::Black;
Console::SetCursorPosition(p.getY() + 30, p.getX() + 5);
cout << " ";
Console::SetCursorPosition(p.getY() + 30, p.getX() + 5+dy);
cout << (char)164;
Thread::Sleep(1000);
}
}
static void moverY(Pos p)
{
int dy = 1;
while (true)
{
if (mapa[p.getX()][p.getY() + dy] == 1){ dy *= -1; }
Console::BackgroundColor = ConsoleColor::Black;
Console::SetCursorPosition(p.getY() + 30, p.getX() + 5);
cout << " ";
Console::SetCursorPosition(p.getY() + 30 + dy, p.getX() + 5);
cout << (char)164;
Thread::Sleep(1000);
}
}
};

Related

define dynamic array inside a struct without causing a segmentation fault

I'm new to c++ and I have to work with dynamic arrays:| I need to define a few dynamic arrays inside my header file and access them from main. The problem is that when I'm defining the arrays inside the structs, I get segmentation faults and don't know how to fix them.
Below is my header file.
I'm aware that there are lots of problems with my code and I could use your help. I'm really stuck here.
Thanks in advance.
I expect this code to work fine with dynamic arrays just like it does with vectors. But it's not.
`
#pragma once
#include <iostream>
#include <functional>
#include <algorithm>
#define children_link_Size 149
#define row 15
#define col 100
using namespace std;
int itemListIndex = 0;
int freqIdx = 0;
int childIdx = 0;
int linkIdx = 0;
namespace std {
template <typename T> T* begin(std::pair<T*, T*> const& p)
{
return p.first;
}
template <typename T> T* end(std::pair<T*, T*> const& p)
{
return p.second;
}
}
struct Node
{
int itemValue{};
int order{ 0 };
int freq{ 0 };
Node* parent{ nullptr };
Node* children{};
Node* links{};
Node() {
children = new Node[children_link_Size];
links = new Node[children_link_Size];
}
explicit Node(int const& p_value, int p_order = 0) :itemValue(p_value), order(p_order)
{
++freq;
cout << " + " << itemValue << " (" << order << ")" << endl;
}
bool operator ==(Node const& p_node) const
{
return itemValue == p_node.itemValue;
}
~Node() {
delete[] children;
delete[] links;
}
};
/*struct mySet {
Node* OrderedItems;
mySet()
{
OrderedItems = new Node[uniqueSize];
}
void insert(Node item)
{
for (int i = 0; i < uniqueSize; i++)
{
for (int j = 0; j < i; j++)
{
if (item == OrderedItems[j])
{
break;
}
else
{
OrderedItems[i] = item;
}
}
}
}
~mySet()
{
delete[] OrderedItems;
}
};*/
struct ItemSupport
{
explicit ItemSupport(int p_minSup) { ItemSupport::minSup = p_minSup; }
Node* Itemset = new (nothrow) Node[row];
Node* OrderedItems = new (nothrow) Node[row];
ItemSupport& operator<<(int const& p_itemValue)
{
static int order = 0;
auto inode = find_if(Itemset, Itemset + row, [&p_itemValue](Node const& p_node)
{
return p_node.itemValue == p_itemValue;
});
if (inode == Itemset + row)
{
Node node(p_itemValue, order);
Itemset[itemListIndex] = node;
itemListIndex++;
++order;
}
else
{
auto& node = (*inode);
++node.freq;
}
return *this;
}
friend ostream& operator<<(ostream& p_os, ItemSupport const& p_itemSupport)
{
ItemSupport* NoDe = {0};
if (NoDe)
{
NoDe->OrderedItems = p_itemSupport.getFrequentItems();
for (Node node : std::make_pair(NoDe->OrderedItems, NoDe->OrderedItems + row))
{
p_os << node.itemValue << ": support " << node.freq << ", order " << node.order << endl;
}
return p_os;
}
}
Node* getItem(int const& p_itemValue)
{
auto inode = find_if(Itemset, Itemset + row, [&p_itemValue](Node const& p_node)
{
return p_node.itemValue == p_itemValue;
});
if (inode != Itemset + row)
{
Node* node = const_cast<Node*>(&(*inode));
return node;
}
return nullptr;
}
static int getMinSup()
{
return minSup;
}
static int minSup;
private:
Node* getFrequentItems() const
{
int j = 0;
for (int i = 0; i < row; i++)
{
if (Itemset[i].freq >= minSup)
OrderedItems[j++] = Itemset[i];
}
return OrderedItems;
}
Node* getUnfrequentItems() const
{
int j = 0;
for (int i = 0; i < row; i++)
{
if (Itemset[i].freq <= minSup)
OrderedItems[j++] = Itemset[i];
}
return OrderedItems;
}
/*~ItemSupport() {
//delete[] Itemset;
//delete[] OrderedItems;
}*/
};
int ItemSupport::minSup = 0;
struct FP_Tree
{
explicit FP_Tree(ItemSupport& p_itemSupport, const int& p_rootValue = int()) :_headItemSupport(p_itemSupport)
{
_root = new Node(p_rootValue);
}
//void construct(Transaction const& p_itemValues)
void construct(int *p_itemValues)
{
// A. Order items into transaction
ItemSupport* ordered = {0};
for (int const& itemValue : std::make_pair(p_itemValues, p_itemValues + row))
{
Node* pNode = _headItemSupport.getItem(itemValue);
if (pNode && pNode->freq >= ItemSupport::getMinSup())
{
if (ordered)
{
ordered->OrderedItems[freqIdx] = *pNode;
freqIdx++;
}
}
}
// B. Create FP_TREE
Node* actualNode = _root;
bool here = true;
string tab;
if (ordered)
{
for (Node const& node : std::make_pair(ordered->OrderedItems, ordered->OrderedItems + row))
{
tab += "\t-";
auto it = actualNode->children;
if (here)
{
auto it = find_if(actualNode->children,
actualNode->children + children_link_Size,
[&node](Node const& nodeTmp) {
return node == (nodeTmp);
});
here &= it != actualNode->children + children_link_Size;
}
if (here)
{
actualNode = it;
++actualNode->freq;
}
else
{
Node* pNode = new Node(node.itemValue);
actualNode->children[childIdx++] = *pNode;
pNode->parent = actualNode;
Node* pNodeHead = _headItemSupport.getItem(node.itemValue);
pNodeHead->links[linkIdx++] = *pNode;
actualNode = pNode;
delete pNode;
}
//cout << tab << actualNode->_itemValue << "(" << actualNode->_freq << ")" << endl;
}
}
//cout << endl;
}
ItemSupport& headItemSupport() const
{
return _headItemSupport;
}
public:
Node* root() const
{
return _root;
}
private:
ItemSupport& _headItemSupport;
Node* _root;
};
`
I expect this code to work fine with dynamic arrays just like it does with vectors
Since you are using C++, do use std::vector -- it will save you a lot of trouble and there is no reason not to.

Exception thrown: read access violation. this->pt_mat was 0x1110112

I got this error while using a double pointer in a class function to set coefficient and using it in the main.
The class function is used in a stand-alone function to set the coefficient using a class type pointer.
The class code is:
class Matrix
{
private:
int size_m, size_n;
double **pt_mat;
public:
Matrix() {};
Matrix(int m, int n)
{
pt_mat = new double *[m];
for (int i = 0; i < m; i++)
{
pt_mat[i] = new double[n];
}
}
void set_size(int m, int n)
{
size_m = m;
size_n = n;
}
void set_coef(int i, int j, double x)
{
pt_mat[i][j] = x;
}
void get_size(int *pt_m, int *pt_n)
{
*pt_m = size_m;
*pt_n = size_n;
}
double get_coef(int i, int j)
{
return pt_mat[i][j];
}
void print(ofstream &fout)
{
fout << size_m << " " << size_n << endl;
int i, j;
for (i = 0; i < size_m; i++)
{
for (j = 0; j < size_n; j++)
{
fout << pt_mat[i][j] << " ";
}
fout << endl;
}
}
void max_min(int *pt_imax, int *pt_jmax, double *pt_max, int *pt_imin, int *pt_jmin, double *pt_min)
{
double max, min;
int i, j, imax = 0, imin = 0, jmax = 0, jmin = 0;
max = pt_mat[0][0];
for (i = 0; i < size_m; i++)
{
for (j = 0; j < size_n; j++)
{
if (pt_mat[i][j] > max)
{
max = pt_mat[i][j];
imax = i;
jmax = j;
}
}
}
*pt_max = max;
*pt_imax = imax;
*pt_jmax = jmax;
min = pt_mat[0][0];
for (i = 0; i < size_m; i++)
{
for (j = 0; j < size_n; j++)
{
if (pt_mat[i][j] < min)
{
min = pt_mat[i][j];
imin = i;
jmin = j;
}
}
}
*pt_min = min;
*pt_imin = imin;
*pt_jmin = jmin;
}
};
The stand-alone function:
void mat_add(Matrix a, Matrix b, Matrix *pt_c)
{
Matrix c;
pt_c = &c;
int a_m, a_n, *p_am = &a_m, *p_an = &a_n;
a.get_size(p_am, p_an);
c.set_size(a_m, a_n);
int m, n, *pt_m = &m, *pt_n = &n;
double coef;
a.get_size(pt_m, pt_n);
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
{
coef = a.get_coef(i, j) + b.get_coef(i, j);
c.set_coef(i, j, coef);
}
}
please help me in this regard if you can. I have no syntax error showing.enter code here

increasing the Framerate to this Processing Script

I'm currently working on this script for a project I'm doing, and I'm not happy with the current frame rate. It's bouncing around FPS, and I need at least 30 so I can further use it in a video installation without lag.
Since my math is terrible, and I didn't quite understand how the original other did the math, I can't figure out where the redundant code is.
I've been working on that for a whole day with no results.
Holler if you need the original .aif or the svg.
I think you can substitute with any kind of audio track, because as much as I can gather, these calculation are run separately.
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.effects.*;
import ddf.minim.signals.*;
import ddf.minim.spi.*;
import ddf.minim.ugens.*;
Minim minim;
AudioPlayer data1;
AudioPlayer data2;
AudioPlayer data3;
AudioPlayer data4;
/* OpenProcessing Tweak of *#*http://www.openprocessing.org/sketch/6598*#* */
/* !do not delete the line above, required for linking your tweak if you upload again */
float grid[][][];
PGraphics boundary;
int page = 0;
int sides = 3;
float w = PI/10;
PShape world;
public void setup() {
size(1920, 1080, FX2D);
//fullScreen(FX2D, 0);
frameRate(30);
grid = new float[2][width-1][height-1];
boundary = createGraphics(width, height);
world = loadShape("world.svg");
makeBoundary(sides);
loadPixels();
minim = new Minim (this);
data1 = minim.loadFile ("indo.aif");
data1.loop();
data1.play();
data2 = minim.loadFile ("chile.aif");
data2.loop();
data2.play();
data3 = minim.loadFile ("fuku.aif");
data3.loop();
data3.play();
data4 = minim.loadFile ("samoa.aif");
data4.loop();
data4.play();
}
void makeBoundary(int sides) {
for (int i=0; i<width-1; i++) {
for (int j=0; j<height-1; j++) {
grid[page][i][j] = 0;
grid[page^1][i][j] = 0;
}
}
boundary.beginDraw();
boundary.background(0);
boundary.fill(255);
boundary.shape(world, 0, 0, 1860, 1020);
boundary.endDraw();
}
public void draw() {
println(frameRate);
float thresh = map(mouseX, 0, width, 0, 255);
oscillator(data1, 380, 700, 32); // Indonesian Wellenquelle
oscillator(data2, 1470, 780, 32);
oscillator(data3, 570, 400, 32);
oscillator(data4, 700, 750, 32);
for (int i=1; i<width-2; i++) {
for (int j=1; j<height-2; j++) {
int wa = boundary.pixels[i+width*j];
float dx = (wa == 0xffffffff) ? 0: (grid[page][i-1][j] + grid[page][i+1][j]);
float dy = (wa == 0xffffffff) ? 0: (grid[page][i][j-1] + grid[page][i][j+1]);
float value = (dx+dy )/2 - grid[page^1][i][j] ;
grid[page^1][i][j] = value * 0.992;
int val = (int) (abs(value) * 512);
val = val > 255 ? 255 : val;
pixels[i+j*width] = 0xFF000000 | val << 16 | val << 8 | val;
}
}
page ^= 1;
updatePixels();
fill(0);
ellipse(380, 700, 64, 64);
ellipse(1470, 780, 64, 64);
ellipse( 570, 400, 64, 64);
ellipse(700, 750, 64, 64);
}
public void oscillator(AudioPlayer data, int x, int y, int r) {
//grid[page][cx][cy] = sou.mix.level() * 60; // Zahl ändert Anzahl von Kreisen/Wellen
//w += PI/16;
int r2 = r * r;
int area = r2 << 2;
int rr = r << 1;
for (int i = 0; i < area; i++)
{
int tx = (i % rr) - r;
int ty = (i / rr) - r;
if (tx * tx + ty * ty <= r2)
grid[page][x + tx][y + ty] = data.mix.level() * 30;
//SetPixel(x + tx, y + ty, c);
}
}
public void mousePressed() {
makeBoundary(++sides);
}
public void keyPressed() {
if (key == ' ') {
sides = 3;
makeBoundary(sides);
}
//saveFrame();
}

Find the word in the stream?

Given an infinite stream of characters and a list L of strings, create a function that calls an external API when a word in L is recognized during the processing of the stream.
Example:
L = ["ok","test","one","try","trying"]
stream = a,b,c,o,k,d,e,f,t,r,y,i,n,g.............
The call to external API will happen when 'k' is encountered, again when the 'y' is encountered, and again at 'g'.
My idea:
Create trie out of the list and navigate the nodes as you read from stream in linear time. But there would be a bug if you just do simple trie search.
Assume you have words "abxyz" and "xyw" and your input is "abxyw".In this case you can't recognize "xyw" with trie.
So search should be modified as below:
let's take above use case "abxyw". We start the search and we find we have all the element till 'x'. Moment you get 'x' you have two options:
Check if the current element is equal to the head of trie and if it is equal to head of trie then call recursive search.
Continue till the end of current word. In this case for your given input it will return false but for the recursive search we started in point 1, it will return true.
Below is my modified search but I think it has bugs and can be improved. Any suggestions?
#define SIZE 26
struct tri{
int complete;
struct tri *child[SIZE];
};
void insert(char *c, struct tri **t)
{
struct tri *current = *t;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
if(current->child[letter] == NULL) {
current->child[letter] = malloc(sizeof(*current));
memset(current->child[letter], 0, sizeof(struct tri));
}
current = current->child[letter];
c++;
}
current->complete = 1;
}
struct tri *t;
int flag = 0;
int found(char *c, struct tri *tt)
{
struct tri *current = tt;
if (current == NULL)
return 0;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
/* if this is the first char then recurse from begining*/
if (t->child[letter] != NULL)
flag = found(c+1, t->child[letter]);
if (flag == 1)
return 1;
if(!flag && current->child[letter] == NULL) {
return 0;
}
current = current->child[letter];
c++;
}
return current->complete;
}
int main()
{
int i;
t = malloc(sizeof(*t));
t->complete = 0;
memset(t, 0, sizeof(struct tri));
insert("weathez", &t);
insert("eather", &t);
insert("weather", &t);
(1 ==found("weather", t))?printf("found\n"):printf("not found\n");
return 0;
}
What you want to do is exactly what Aho-Corasick algorithm does.
You can take a look at my Aho-Corasick implementation. It's contest-oriented, so maybe not focused on readability but I think it's quite clear:
typedef vector<int> VI;
struct Node {
int size;
Node *fail, *output;
VI id;
map<char, Node*> next;
};
typedef pair<Node*, Node*> P;
typedef map<char, Node*> MCP;
Node* root;
inline void init() {
root = new Node;
root->size = 0;
root->output = root->fail = NULL;
}
Node* add(string& s, int u, int c = 0, Node* p = root) {
if (p == NULL) {
p = new Node;
p->size = c;
p->fail = p->output = NULL;
}
if (c == s.size()) p->id.push_back(u);
else {
if (not p->next.count(s[c])) p->next[s[c]] = NULL;
p->next[s[c]] = add(s, u, c + 1, p->next[s[c]]);
}
return p;
}
void fill_fail_output() {
queue<pair<char, P> > Q;
for (MCP::iterator it=root->next.begin();
it!=root->next.end();++it)
Q.push(pair<char, P> (it->first, P(root, it->second)));
while (not Q.empty()) {
Node *pare = Q.front().second.first;
Node *fill = Q.front().second.second;
char c = Q.front().first; Q.pop();
while (pare != root && !pare->fail->next.count(c))
pare=pare->fail;
if (pare == root) fill->fail = root;
else fill->fail = pare->fail->next[c];
if (fill->fail->id.size() != 0)
fill->output = fill->fail;
else fill->output = fill->fail->output;
for (MCP::iterator it=fill->next.begin();
it!=fill->next.end();++it)
Q.push(pair<char,P>(it->first,P(fill,it->second)));
}
}
void match(int c, VI& id) {
for (int i = 0; i < id.size(); ++i) {
cout << "Matching of pattern " << id[i];
cout << " ended at " << c << endl;
}
}
void search(string& s) {
int i = 0, j = 0;
Node *p = root, *q;
while (j < s.size()) {
while (p->next.count(s[j])) {
p = p->next[s[j++]];
if (p->id.size() != 0) match(j - 1, p->id);
q = p->output;
while (q != NULL) {
match(j - 1, q->id);
q = q->output;
}
}
if (p != root) {
p = p->fail;
i = j - p->size;
}
else i = ++j;
}
}
void erase(Node* p = root) {
for (MCP::iterator it = p->next.begin();
it != p->next.end(); ++it)
erase(it->second);
delete p;
}
int main() {
init();
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
add(s, i);
}
fill_fail_output();
string text;
cin >> text;
search(text);
erase(root);
}

VC++ threads deadlocked

The following program goes into a deadlock. Can anyone please tell me why?
#include<cstdlib>
#include<windows.h>
#include<iostream>
using namespace std;
class CircularQueue
{
public:
CircularQueue(int s)
{
size = s;
array = (int*)malloc(sizeof(int) * size);
head = tail = -1;
InitializeCriticalSection(&critical_section);
}
CircularQueue(void)
{
size = default_size;
array = (int*)malloc(sizeof(int) * size);
head = tail = -1;
InitializeCriticalSection(&critical_section);
}
void initialize(int s)
{
EnterCriticalSection(&critical_section);
size = s;
array = (int*)realloc(array, sizeof(int) * size);
head = tail = -1;
LeaveCriticalSection(&critical_section);
}
void enqueue(int n)
{
EnterCriticalSection(&critical_section);
tail = (tail + 1) % size;
array[tail] = n;
LeaveCriticalSection(&critical_section);
}
int dequeue(void)
{
EnterCriticalSection(&critical_section);
head = (head + 1) % size;
return array[head];
LeaveCriticalSection(&critical_section);
}
private:
int *array;
int size;
int head, tail;
CRITICAL_SECTION critical_section;
bool initialized;
static const int default_size = 10;
};
DWORD WINAPI thread1(LPVOID param)
{
CircularQueue* cqueue = (CircularQueue*)param;
cqueue->enqueue(2);
cout << cqueue->dequeue() << endl;
return 0;
}
DWORD WINAPI thread2(LPVOID param)
{
CircularQueue* cqueue = (CircularQueue*)param;
cqueue->enqueue(3);
cout << cqueue->dequeue() << endl;
return 0;
}
int main(void)
{
HANDLE thread1_handle;
HANDLE thread2_handle;
CircularQueue cqueue;
HANDLE array[2];
thread1_handle = CreateThread(NULL, 0, thread1, &cqueue, 0, NULL);
thread2_handle = CreateThread(NULL, 0, thread2, &cqueue, 0, NULL);
array[0] = thread1_handle;
array[1] = thread2_handle;
WaitForMultipleObjects(1, array, TRUE, INFINITE);
CloseHandle(thread1_handle);
CloseHandle(thread2_handle);
printf("end\n");
return 0;
}
In dequeue(), you have a return statement before the LeaveCriticalSection() call. If you had compiler warnings turned up higher, it would probably have told you about this!

Resources