i have assigment to create c++ program which will multiple 2 uknown size matrix using fork and shared memory, I have write this code but at the end for multiplication result i get all zeros. Sorry for mess code im new in this.
`
`#include<iostream>
#include<math.h>
#include<vector>
#include<signal.h>
#include<unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<sys/wait.h>
using namespace std;
int l, m, n, job_numb;
key_t id_shared_mem;
int **B, **C, **A;
int **generateMatrix(int **matrix, int iterator, int vel){
for (int i = 0; i < iterator; i++)
{
matrix[i] = new int[vel];
for (int j = 0; j < vel; j++)
{
matrix[i][j] = (rand() % 9);
}
}
return matrix;
}
int **generateMatrixC(int **matrix, int iterator, int vel)
{
for (int i = 0; i < iterator; i++)
{
matrix[i] = new int[vel];
}
return matrix;
}
void *writeMatrixResult(int **matrix, int stupac, int red)
{
for (int i = 0; i < stupac; i++)
{
for (int j = 0; j < red; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
return NULL;
}
void write()
{
cout << "Mnozenik = " << endl;
writeMatrixResult(A, l, m);
cout << "Mnozitelj = " << endl;
writeMatrixResult(B, m, l);
cout << "Umnozak = " << endl;
writeMatrixResult(C, l, l);
}
void abort(int sig) {
if (sig == SIGINT) {
for (int i = 0; i < job_numb; i++) wait(NULL);
shmdt(A);
shmdt(B);
shmctl(id_shared_mem, IPC_RMID, NULL);
} else {
write();
shmdt(A);
shmdt(B);
shmctl(id_shared_mem, IPC_RMID, NULL);
}
exit(0);
}
void proces(int procesId)
{
while (job_numb > procesId)
{
int i = 0;
while (i < l)
{
int j = 0;
C[procesId][i] = 0;
while (m > j)
{
C[procesId][i] = C[procesId][i] + A[procesId][j] * B[j][i];
j++;
}
i++;
}
procesId++;
}
}
int main(int argc, char ** argv) {
if (argc != 4) {
cout << " unesite 3 argumenta!" << endl;
return 0;
}
l = atoi(argv[1]);
m = atoi(argv[2]);
n = atoi(argv[3]);
job_numb = l / n;
if (l % n) {
job_numb++;
}
id_shared_mem = shmget(IPC_PRIVATE, sizeof(int) * 10, 0600);
sigset(SIGINT, abort);
A = (int **)shmat(id_shared_mem, NULL, 0);
B = A + l;
C = B + l * m*m;
A = new int *[l];
B = new int *[m];
C = new int *[l];
srand(time(NULL));
A = generateMatrix(A,l, m );
B = generateMatrix(B,m,l);
C = generateMatrixC(C,l,l);
for (int i = 0; i < n; i++)
{
switch (fork()) {
case 0: { //dijete
proces(i);
exit(0);
}
case -1: { //greska
cout << "Fatalna pogreska!" << endl;
exit(1);
}
}
}
for (int i = 0; i < job_numb; i++) wait(NULL);
abort(0);
}`
`
i have try to assign only one value to matrix C like c[1][1] = 2 in proces function to see if it will write any, but still im getting all zeros on printl.
Related
I am trying to implement Sequence alignment problem (Needleman-Wunsch algorithm) using p-Threads. I am confused how to map the concept of multi threading in this particular serial problem. The code of serial computation of sequence alignment is enclosed below.(Just Matrix calculation part)
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
class Matrix
{
private:
int x;
int y;
int** mat;
string gene1;
string gene2;
int match_penalty;
int mismatch_penalty;
int gap_penalty;
int minimum_penalty;
public:
Matrix(int gene1Len, int gene2Len)
{
x = gene2Len + 1; //gene2 length
y = gene1Len + 1; //gene 1 length;
mat = new int* [x];
for (int i = 0; i < x; i++)
mat[i] = new int[y];
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
mat[i][j] = 0;
}
}
//Default Penalties
match_penalty = 1;
mismatch_penalty = 3;
gap_penalty = 2;
minimum_penalty=0;
}
void Print_Matrix()
{
cout<<"\n";
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
cout << mat[i][j] << "\t";
}
cout << "\n";
}
}
void setGenes(string gene1, string gene2)
{
this->gene1 = gene1;
this->gene2 = gene2;
}
void setPenalty(int mismatch, int gp,int match)
{
mismatch_penalty = mismatch;
gap_penalty = gp;
match_penalty=match;
}
void setMatrix()
{
//1st row and 1st Column values
for (int i = 0; i < x; i++)
{
mat[i][0] = i * gap_penalty;
}
for (int i = 0; i < y; i++)
{
mat[0][i] = i * gap_penalty;
}
// Other matrix values
for (int i = 1; i < x; i++)
{
for (int j = 1; j < y; j++)
{
if (gene1[j - 1] == gene2[i - 1]) //Similar gene values (A==A ||T==T)
{
mat[i][j] = mat[i - 1][j - 1]+match_penalty;
}
else
{
mat[i][j] = max({ mat[i - 1][j - 1] + mismatch_penalty , mat[i - 1][j] + gap_penalty, mat[i][j - 1] + gap_penalty });
}
}
}
}
};
int main()
{
string gene1 = "ACCA";
string gene2 = "CCA";
int matchPenalty;
int misMatchPenalty ;
int gapPenalty ;
cout<<"Enter the value of Match Penalty" << endl;
cin >> matchPenalty;
cout<<"Enter the value of misMatchPenalty Penalty" << endl;
cin >> misMatchPenalty;
cout<<"Enter the value of gapPenalty Penalty" << endl;
cin >> gapPenalty;
Matrix dp(gene1.length(), gene2.length());
dp.setGenes(gene1, gene2);
dp.setPenalty(misMatchPenalty, gapPenalty,matchPenalty);
dp.setMatrix();
dp.Print_Matrix();
}
How can I implement the above problem in P-threads? So far, I have used two threads to calculate matrix values of 1st column and 1st row simultaneously.But I have no idea how to compute all values of matrix in parallel. Kindly see my source code:
#include<string>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<pthread.h>
using namespace std;
//Global variables --shared by all threads
int matchPenalty;
int misMatchPenalty;
int gapPenalty;
struct gene_struct {
string gene1;
string gene2;
int rowSize;
int colSize;
int **mat;
};
void* set_matrix_row(void *args)
{
struct gene_struct *shared_block = (struct gene_struct *) args;
for (int i = 0; i < shared_block->rowSize; i++)
{
shared_block->mat[i][0] = i * gapPenalty;
}
return NULL;
}
void *set_matrix_column(void *args)
{
struct gene_struct *shared_block = (struct gene_struct *) args;
for (int i = 0; i < shared_block->colSize; i++)
{
shared_block->mat[0][i] = i * gapPenalty;
}
return NULL;
}
void set_Matrix_Diagnol(struct gene_struct shared_block)
{
//How Should I calculate rest of the matrix values using Pthreads?
}
void Print_Matrix(struct gene_struct shared_block)
{
cout<<"\n";
for (int i = 0; i < shared_block.rowSize; i++)
{
for (int j = 0; j < shared_block.colSize; j++)
{
cout << shared_block.mat[i][j] << "\t";
}
cout << "\n";
}
}
int main()
{
pthread_t ptid1, ptid2;
string gene1, gene2;
struct gene_struct shared_block;
cout << "Enter First Gene : ";
cin >> gene1;
cout << "Enter Second Gene : ";
cin >> gene2;
cout<<"Enter the value of Match Penalty" << endl;
cin >> matchPenalty;
cout<<"Enter the value of misMatchPenalty Penalty" << endl;
cin >> misMatchPenalty;
cout<<"Enter the value of gapPenalty Penalty" << endl;
cin >> gapPenalty;
shared_block.gene1 = gene1;
shared_block.gene2 = gene2;
shared_block.rowSize = gene2.length()+1;
shared_block.colSize = gene1.length()+1;
shared_block.mat = new int* [shared_block.rowSize]; //col = gene2+1
for (int i = 0; i < shared_block.rowSize; i++)
{
shared_block.mat[i] = new int[shared_block.colSize];
}
pthread_create(&ptid1, NULL, &set_matrix_row, (void *)&shared_block);
pthread_create(&ptid2, NULL ,&set_matrix_column, (void *)&shared_block);
pthread_join(ptid1,NULL);
pthread_join(ptid2,NULL);
Print_Matrix(shared_block);
}
I have following code which is simply tokenizing an array and then deviding on the basis of '<' and '>' characters. It is running fine in VS community 2019 but when I run it in Linux using g++ command it gives
Free(): invalid pointer
and
Aborted (core dumped)
errors. What am I doing wrong.
PS: error seems to be in the instructions where I am deallocating b in rangbrk and langbrk because when I put it in comments it runs fine in Linux too. But it runs fine in VS 2019 anyways.
//#include <sys/types.h>
//#include <sys/wait.h>
//#include <sys/stat.h>
#include <fcntl.h>
//#include <unistd.h>
#include<string.h>
#include<stdio.h>
#include<fstream>
#include<iostream>
#include<stdlib.h>
using namespace std;
//_________________________________________________________
int reads(char str[])
{//a simple function to get input
int s = 1;
char buffer[100];
cout << "enter command" << endl;
cin.getline(buffer, 100);
if (strlen(buffer) == 0)
{
cout << "Couldnt get input\n";
return 0;
}
for (int i = 0; i <= strlen(buffer); i++)
{
str[i] = buffer[i];
if (buffer[i] == 32)
s++;
}
return s;
}
//____________________________________________________________
int tokenizing(char** a, char str[], char buff[50], int x)
{//a function to devide a complete string into smaller parts
//also stores '/bin/command' into buff to pass as first parameter of execvp
int k = 0, m = 0;
bool check = false;
for (int i = 0; i < x; i++)
{
a[i] = new char[50];
for (int j = 0; str[k] != 32; j++)
{
if (str[k] == 0)
{
check = true;
break;
}
a[i][j] = str[k];
if (i == 0)
buff[j + 5] = str[k];
k++;
a[i][j + 1] = 0;
if (i == 0)
buff[j + 6] = 0;
}
m++;
k++;
if (check)
break;
}
return m;
}
//__________________________________________________________
void rangbrk(char**& a, char**& b, int& x, char filename[])
{//saperates the array before and after '>'
for (int i = 0; i < (x - 2); i++)
{
b[i] = new char[50];
for (int j = 0; j < 50; j++)
{
b[i][j] = a[i][j];
}
}
b[x - 2] = NULL;
for (int i = 0; i < 50; i++)
{
filename[i] = a[x - 1][i];
}
char** c;//temprory pointer to swap a and b
c = a;
a = b;
b = c;
x = x - 2;
for(int i=0;i<x-1;i++)
{
delete [] b[i];
}
b=NULL;
}
//__________________________________________________________
void langbrk(char** &a, char** &b, int& x, int index, char filename[])
{//saperates the array before and after '<'
int k = 0;
for (int i = 0; i < x; i++)
{
if ((i != index) && (i != index - 1))
{
b[k] = new char[50];
for (int j = 0; j < 50; j++)
{
b[k][j] = a[i][j];
}
k++;
}
}
b[x - 2] = NULL;
for (int i = 0; i < 50; i++)
{
filename[i] = a[index - 1][i];
}
char** c;//temprory pointer to swap a and b
c = a;
a = b;
b = c;
x = x - 2;
for(int i=0;i<x-1;i++)
{
if(b[i]!=NULL)
delete [] b[i];
}
b=NULL;
}
//__________________________________________________________
int main()
{
char buff[50] = { "/bin/" };
char str[100];
char exit[5] = { 'e','x','i','t',0 };
char outfile[50];
char infile[50];
int x = reads(str);
char** a;
a = new char* [x];
int s = tokenizing(a, str, buff, x);
a[s] = NULL;
bool flag = false;
for (int i = 0; a[i] != NULL; i++)
cout << a[i] << endl;
cout << s << endl;;
for (int i = 0; i < s; i++)
{
if (a[i][0] == '>')//checks if it need to print in a file
{
cout << i;
char** b;
b = new char* [s - 2];
rangbrk(a, b, s, outfile);
flag = true;
cout << "New" << endl;
for (int j = 0; j < s; j++)
cout << a[j] << endl;
i = 0;
}
else if (a[i][0] == '<')
{
cout << i;
char** c;
c = new char * [s - 2];
langbrk(a, c, s, i, infile);
cout << "New" << endl;
for (int j = 0; j < s; j++)
cout << a[j] << endl;
i = 0;
}
}
}
The reads function gets input, tokenizing tokenized the string in form of words. langbrk copies the string having index 1 less than index of '<' in infile and removes them both from main char** a. rangbrk removes '>' and string succeeding it from a and stores it in outfile
There is a fully working Dijkstra algorithm that takes values from a file (or writes a new one) and writes data to a matrix. How can you improve the program using OpenMP so that its speed is significantly increased? New to openMP, had little experience with common matrices, mostly parallelization "for".
I attach all the code below:
#include <iostream>
#include <fstream>
#include <string>
#include <climits>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <locale.h>
#include <chrono>
using namespace std;
class Timer
{
private:
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
chrono::time_point<clock_t> m_beg;
public:
Timer() : m_beg(clock_t::now())
{
}
double elapsed() const
{
return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
}
};
void fillingArray(int** arr, int c, string filename) {
ofstream fout(filename);
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < c; i++){
for (int j = 0; j < c; j++) {
arr[i][j] = arr[j][i] = rand() % 10 + 1;
}
}
for (int i = 0; i < c; i++) {
fout << endl;
for (int j = 0; j < c; j++) {
fout << setw(5) << arr[i][j];
}
}
}
void read(int** arr, int c, string filename) {
char answer;
ifstream file;
file.open(filename);
if (!file) {
fillingArray(arr, c, filename);
}
else {
cout << "File found\nWant to overwrite it? (y / n)\n";
cin >> answer;
if (answer == 'y' || answer == 'Y') {
fillingArray(arr, c, filename);
}
else {
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
file >> arr[i][j];
}
}
}
}
file.close();
}
void Dijkstra(int** arr, int c, int st)
{
Timer t;
int count, index, i, u, m = st + 1;
int* distance = (int*)malloc(c * sizeof(int*));
bool* visited = new bool[c];
for (i = 0; i < c; i++)
{
distance[i] = INT_MAX; visited[i] = false;
}
distance[st] = 0;
for (count = 0; count < c - 1; count++)
{
int min = INT_MAX;
for (i = 0; i < c; i++)
if (!visited[i] && distance[i] <= min)
{
min = distance[i]; index = i;
}
u = index;
visited[u] = true;
for (i = 0; i < c; i++)
if (!visited[i] && arr[u][i] && distance[u] != INT_MAX &&
distance[u] + arr[u][i] < distance[i])
distance[i] = distance[u] + arr[u][i];
}
double time = t.elapsed();
cout << "Cost of the path from the initial peak to the rest:\t\n";
for (i = 0; i < c; i++) if (distance[i] != INT_MAX)
cout << m << " > " << i + 1 << " = " << distance[i] << endl;
else cout << m << " > " << i + 1 << " = " << "route not available" << endl;
cout << "Time passed: " << time << "с\n";
delete[] visited;
delete[] distance;
}
int main()
{
string filename, rash;
filename = "arr";
rash = ".dat";
int c;
cout << "Enter the number of ribs:\n";
cin >> c;
int** arr = (int**)malloc(c * sizeof(int*));
for (int i = 0; i < c; i++) {
arr[i] = (int*)malloc(c * sizeof(int));
}
filename += to_string(c) + rash;
read(arr, c, filename);
Dijkstra(arr, c, 0);
delete[] arr;
}
After the function is called, the main() function does not execute.
I implemented dijkstra's algorithm in C++, adding "cout<<"called main\n" to the first line of the main () function to see if the main function was properly called.But if I call the function dijkstra(mygragh g,int dis[],int pre[],int v0), the program would have no output, and "called main" can be output normally without using the function.Can anyone suggest why it would happend?
#include <iostream>
#include <vector>
using namespace std;
struct mygragh{
int map[1000][1000];
int e;
int n;
};
void dijkstra(mygragh g,int dis[],int pre[],int v0){
cout << "called dijkstra\n";
int n = g.n;
vector<bool> visit(n, false);
for (int i = 0; i < n;i++){
if(g.map[v0][i]!=INT_MAX){
dis[i] = g.map[v0][i];
pre[i] = v0;
}
else{
dis[i] = INT_MAX;
pre[i] = -1;
}
}
visit[v0]=true;
for(int i=0;i<n;i++){
int min = INT_MAX,u=-1;
for (int j = 0; j < n;j++){
if(visit[j]==false&&dis[j]<min){
min = dis[j];
u = j;
}
}
if(u==-1){
break;
}
visit[u] = true;
for (int j = 0; j < n;j++){
if(visit[j]==false&&dis[j]>dis[u]+g.map[u][j]){
dis[j] = dis[u] + g.map[u][j];
pre[j] = u;
}
}
}
}
int main(){
cout << "called main\n";
mygragh g;
int n = 5;
int e = 7;
g.n = n;
g.e = e;
int dis[n];
int pre[n];
for (int i = 0; i < n;i++){
for (int j = 0; j < n;j++){
g.map[i][j] = 100;
}
}
//fill(g.map, g.map + n * n, INT_MAX);
for (int i = 0; i < n;i++){
g.map[i][i] = 0;
}
for (int i = 0; i < e;i++){
int c1, c2, l;
cin >> c1 >> c2 >> l;
g.map[c1][c2] = l;
g.map[c2][c1] = l;
}
dijkstra(g, dis, pre, 0);
cout << dis[1];
return 0;
}
Hi i have a problem with my code, i try sort array by counting sort (it must be stable sort), but my code doesn't work. I try implemented counting-sort from some wbesite, but it was in c# and I'm not sure s it done correctly. Can you tell me what is wrong with it?
#include <stdio.h>
#include <iostream>
using namespace std;
void sort_with_show(int **a, int rozmiar, int polecenie)
{
int y, d;
for (int i = 0; i< rozmiar - 1; i++)
{
for (int j = 0; j < rozmiar - 1 - i; j++)
{
if (a[j + 1][0] < a[j][0])
{
y = a[j][0];
a[j][0] = a[j + 1][0];
a[j + 1][0] = y;
}
}
}
for (int i = 0; i < rozmiar; i++)
{
//cout << tablica[i].x << " " << tablica[i].y << "\n";
if (polecenie == 0)
{
cout << a[i][0] << '\n';
}
else if (polecenie == 1)
{
cout << a[i][0] << "," << a[i][1] << "\n";
}
}
}
int main()
{
int rozmiar = 0;
int polecenie = 0;
char t[20] = { '\0' };
char *p, *q;
int liczba = 0;
int calaLiczba = 0;
bool isY = false;
cin >> rozmiar;
int ** a = new int *[rozmiar];
for (int i = 0; i < rozmiar; i++)
a[i] = new int[2];
cin.ignore();
int i = 0;
while(i < rozmiar)
{
fgets(t, sizeof t, stdin);
for (p = t, q = t + sizeof t; p < q; p++)
{
if (*p >= 48 && *p <= 57)
{
liczba = *p - 48;
calaLiczba = calaLiczba * 10 + liczba;
}
if (*p == ' ')
{
a[i][0] = calaLiczba;
isY = true;
calaLiczba = 0;
liczba = 0;
}
if (*p == '\n')
{
a[i][1] = calaLiczba;
isY = false;
}
}
for (int j = 0; j < 20; j++)
t[j] = '\0';
liczba = 0;
calaLiczba = 0;
isY = false;
i++;
}
cin >> polecenie;
cin.ignore();
sort_with_show(a, rozmiar, polecenie);
return 0;
}