how to parallel or multithreading 2 function in C++? - multithreading

I'm a beginner at parallel programming. I have 2 function in my code that I want run this 2 function in parallel (multiThread). can you help me?
func 1:
void Navigation::test_end(Graph::Node *node, dtPolyRef endRef, const float *endPos, int endIdPos)
{
int k=0;
//std::ofstream fout("v4.txt", std::ios_base::app | std::ios_base::out);
auto it2 = myMap2.equal_range(endRef);
for (auto it = it2.first; it != it2.second; ++it) {
int m_npolys = 0;
int n=0;
dtPolyRef m_polys[MAX_POLYS];
int j = it->second.size();
for(int i=0;i<j-1;i++){
if(it->second[i]>0){
m_polys[m_npolys++] =it->second[i];
// fout <<it->second[i]<<" ";
}
currentGraph.AddIntraEdge(node->idNode,endIdPos, node->edges[k].idPos, it->second[j-1], m_polys ,m_npolys); //n=m_npolys
k++;
}
}
==========
func 2:
void Navigation::test_start(Graph::Node *node, dtPolyRef startRef, const float *startPos, int startIdPos)
{
int k=0;
//std::ofstream fout("v4.txt", std::ios_base::app | std::ios_base::out);
auto it2 = myMap2.equal_range(startRef);
for (auto it = it2.first; it != it2.second; ++it) {
int m_npolys = 0;
int n=0;
dtPolyRef m_polys[MAX_POLYS];
int j = it->second.size();
for(int i=0;i<j-1;i++){
if(it->second[i]>0){
m_polys[m_npolys++] =it->second[i];
// fout <<it->second[i]<<" ";
}
currentGraph.AddIntraEdge(node->idNode,startIdPos, node->edges[k].idPos, it->second[j-1], m_polys ,m_npolys); //n=m_npolys
k++;
}
}
now i want to run this 2 function in parallel mode in the main function :
test_start(sNode,startRef,startPos,startIdPos);
test_end(eNode,endRef,endPos, endIdPos);

Related

Processor implementation

Can you help me about the code below.
Is it writing 1 to the data memory or to the internal memory.
there are only 32 internal registers
The processor is 32 bit risc-v based
thanks in advance
#include "string.h"
#define DEBUG_IF_ADDR 0x00002010
void bubble_sort(int* arr, int len)
{
int sort_num;
do
{
sort_num = 0;
for(int i=0;i<len-1;i++)
{
if(*(arr+i) > *(arr+i+1))
{
int tmp = *(arr+i);
*(arr+i) = *(arr+i+1);
*(arr+i+1) = tmp;
sort_num++;
}
}
}
while(sort_num!=0);
}
int main()
{
int unsorted_arr[] = {195,14,176,103,54,32,128};
int sorted_arr[] = {14,32,54,103,128,176,195};
bubble_sort(unsorted_arr,7);
int *addr_ptr = DEBUG_IF_ADDR;
if(memcmp((char*) sorted_arr, (char*) unsorted_arr, 28) == 0)
{
//success
*addr_ptr = 1;
}
else
{
//failure
*addr_ptr = 0;
}
return 0;
}

Hi, I wrote code in C++ fot linear search but it displays the index of searched elemet twice with second index value as random garbage value

Here is the code.what i did is implement linear search on some elements of the array and the push searched elements in stack,afterwards I print the popped elements from stack and print them.But in search function it displays two index values.
using namespace std;
int searched[10];
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
int main(void)
{
int arr[15] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
int x = 0;
for(int i=0;i<8;i++)
{
x++;
int result = search(arr, n, x);
cout << "searched Element is " << result<<"\t\t";
push(result);
pop();
}
return 0;
}```
There are two issues that lead to this confusing result.
First, if I am not mistaken the search function, which was written like this:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
is parsed similarly to the following:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
cout<<"The element is found at the index"<<i<<"\n\n";
}
}
return x;
}
Presumably you meant this:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
}
}
Second, since the global n starts at the value 100, the search loop runs off the end of the length 15 array, into other memory. This is probably undefined behavior.

Matrix multiplication with threads and semaphore

I have to implement matrix multiplication with threads using semaphore. The problem is I don't understand how semaphore works and my result matrix is filled with zeros and program hangs. Could you explain me what I'm doing wrong?
Here's my code:
class Program
{
private static Semaphore semaphore = new Semaphore(0, 1);
static void Main(string[] args)
{
int size;
int[,] a = null, b = null, c = null;
bool isNumeric;
do
{
Console.Write("Insert size: ");
isNumeric = int.TryParse(Console.ReadLine(), out size);
}
while (!isNumeric || size < 2);
Console.WriteLine();
SquareMatrix.Init(size, ref a);
SquareMatrix.Init(size, ref b);
SquareMatrix.Init(size, ref c);
SquareMatrix.Fill(a);
SquareMatrix.Fill(b);
Console.WriteLine("Matrix 1:\n");
SquareMatrix.Display(a);
Console.WriteLine("Matrix 2:\n");
SquareMatrix.Display(b);
Console.WriteLine();
DateTime start = DateTime.Now;
for (int i = 0; i < size; i++)
{
Thread thread = new Thread(() => Multiply(i, size, a, b, c));
thread.Name = i.ToString();
thread.Start();
}
DateTime stop = DateTime.Now;
Console.WriteLine("Result (" + (stop - start).TotalMilliseconds + " ms):\n");
SquareMatrix.Display(c);
Console.ReadLine();
}
public static void Multiply(int i, int size, int[,] a, int[,] b, int[,] c)
{
semaphore.WaitOne();
for (int j = 0; j < size; j++)
{
c[i, j] = 0;
for (int k = 0; k < size; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
semaphore.Release();
}
}
And SquareMatrix code:
static class SquareMatrix
{
private static readonly Random random = new Random();
public static void Init(int size, ref int[,] array)
{
array = new int[size, size];
}
public static void Fill(int[,] array)
{
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
{
array[i, j] = random.Next(-10, 10);
}
}
}
public static void Display(int[,] array)
{
string result = "";
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
result += array[i, j] + " ";
result += "\n";
}
Console.Write(result + "\n");
}
}

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