Why the output goes wrong when using pthread_join? - linux

I am still learning about threads and I was trying to solve this problem in my code, when I am putting the pthread_join(thread[i],NULL) outside the loop that is creating the threads it always gives me wrong output and Thread with ID = 0 will not work(call the median func) and the last thread will work two times, for better understanding see the output below:
ThreadID= 0, startRow= 0, endRow= 0 // first thread doesn't call the median func
ThreadID= 1, startRow= 1, endRow= 1
ThreadID 1 numOfBright 0 numOfDark 1 numOfNormal 4
ThreadID= 2, startRow= 2, endRow= 2
ThreadID 2 numOfBright 0 numOfDark 1 numOfNormal 4
ThreadID= 3, startRow= 3, endRow= 3
ThreadID 3 numOfBright 0 numOfDark 0 numOfNormal 5
ThreadID= 4, startRow= 4, endRow= 4
ThreadID 4 numOfBright 0 numOfDark 5 numOfNormal 0
ThreadID 4 numOfBright 0 numOfDark 5 numOfNormal 0 // last thread is calling the median func two times.
This is the part of the code that prints the start and end row of each thread.
pthread_t* threads = new pthread_t[num_threads];
struct Th_Range* RANGE = (struct Th_Range*)malloc(sizeof(struct Th_Range*));
int thread_status;
RANGE->SizeOfImage = r; // 2d array with size (n*n) so rows(r) = columns(c)
if (n == num_threads) { //rows = num of threads then every thread will work in a single row
for (int i = 0; i < num_threads; i++) {
RANGE->ThreadId = i;
RANGE->StartRow = RANGE->EndRow = i;
cout << "ThreadID= " << i << ", startRow= " << RANGE->StartRow << ", endRow= " << RANGE->EndRow << endl;
thread_status = pthread_create(&threads[i], NULL, Median, RANGE);
if (thread_status)
exit(-1);
} //for loop ends here
for (int i = 0; i < num_threads; i++)
pthread_join(threads[i],NULL);
} //end of if statement
Here is the part of the code if needed with the median function and the above if statement.
#include <iostream>
#include <bits/stdc++.h>
#include <pthread.h>
pthread_mutex_t Lock;
pthread_mutex_t Pixels;
pthread_mutex_t Pixels2;
using namespace std;
int numOfBright, numOfDark, numOfNormal;
int** Oimage, ** Fimage; //original and filtered image
struct Th_Range {
int SizeOfImage;
int StartRow;
int EndRow;
int ThreadId;
};
void* Median(void* par)
{
struct Th_Range* Num = (struct Th_Range*)par;
int StartRow = Num->StartRow;
int EndRow = Num->EndRow;
int Size = Num->SizeOfImage;
int Neighbour[9] = { 0 };
int dark = 0, bright = 0, normal = 0;
if (EndRow == StartRow)
EndRow += 2;
else
EndRow++;
for (int i = StartRow +1; i < EndRow ; i++)
{
for (int j = 1; j < Size - 1; j++)
{
Neighbour[0] = Oimage[i - 1][j - 1];
Neighbour[1] = Oimage[i - 1][j];
Neighbour[2] = Oimage[i - 1][j + 1];
Neighbour[3] = Oimage[i][j - 1];
Neighbour[4] = Oimage[i][j];
Neighbour[5] = Oimage[i][j + 1];
Neighbour[6] = Oimage[i + 1][j - 1];
Neighbour[7] = Oimage[i + 1][j];
Neighbour[8] = Oimage[i + 1][j + 1];
pthread_mutex_lock(&Pixels); //it can be moved only to lock the Fimage and the numOfBright or any other global variables
sort(Neighbour, Neighbour + 9);
Fimage[i][j] = Neighbour[4];
if (Neighbour[4] > 200) {
bright++;
numOfBright++;
}
else if (Neighbour[4] < 50) {
dark++;
numOfDark++;
}
else {
normal++;
numOfNormal++;
}
pthread_mutex_unlock(&Pixels);
}
}
pthread_mutex_lock(&Pixels2); //when I try to remove this lock the output gets interrupted
cout << "ThreadID " << Num->ThreadId << " numOfBright " << bright << " numOfDark " << dark << " numOfNormal " << normal<<endl;
pthread_mutex_unlock(&Pixels2);
pthread_exit(NULL);
}
int main(int argc, char* argv[])
{
int num_threads, n, r, c; // n is the size of the matrix r and c are rows and columns
numOfNormal = numOfDark = numOfBright = 0;
if (argc >= 2)
num_threads = atoi(argv[1]);
else
exit(-1);
ifstream cin("input.txt");
cin >> n;
r = c = n + 2;
Oimage = new int* [r]();
Fimage = new int* [r]();
for (int i = 0; i < c; i++)
{
Oimage[i] = new int[c]();
Fimage[i] = new int[c]();
}
for (int i = 1; i < r - 1; i++)
for (int j = 1; j < c - 1; j++)
cin >> Oimage[i][j];
pthread_t* threads = new pthread_t[num_threads];
struct Th_Range* RANGE = (struct Th_Range*)malloc(sizeof(struct Th_Range*));
RANGE->SizeOfImage = r;
if (n == num_threads) { //rows = num of threads then every thread will work in a single row
//n+2
int thread_status;
for (int i = 0; i < num_threads; i++) {
RANGE->ThreadId = i;
RANGE->StartRow = RANGE->EndRow = i;
// pthread_mutex_lock(&Lock);
cout << "ThreadID= " << i << ", startRow= " << RANGE->StartRow << ", endRow= " << RANGE->EndRow << endl;
thread_status = pthread_create(&threads[i], NULL, Median, RANGE);
if (thread_status)
exit(-1);
}
}
I tried to move pthread_join inside the loop of pthread_create it gives a correct output but of course it is a wrong solution. I have no idea what to do next. Thanks in advance

Maybe you should use #include
or (using namespace sff) it must work

Related

merge sorted array elements not printing

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void merge(vector<int>& nums1, int n, vector<int>& nums2, int m) {
int i = n - 1, j = m - 1, k = n + m - 1;
while (i >= 0 && j >= 0) {
if (nums1[i] < nums2[j]) {
nums1[k--] = nums2[j--];
} else {
nums1[k--] = nums1[i--];
}
}
while (j >= 0) {
nums1[k--] = nums2[j--];
}
for (int i = 0; i < nums1.size(); i++) {
cout << nums1[i] << " ";
}
}
int main() {
vector<int> i = { 1, 3, 5, 7 };
vector<int> j = { 0, 2, 4, 6, 8, 10 };
int n = i.size();
int m = j.size();
merge(i, n, j, m);
return 0;
}
I want to print the merged sorted array now, but its always printing unmerged array(ie: the array before merging)
I tried many solutions and in one its just giving unsorted garbage kind of values.
C++ vectors, unlike javascript arrays, are not automatically resized upon storing elements at index values greater or equal to the allocated length. The behavior is undefined and could cause a segmentation fault or other program failures.
You must resize nums1 using the resize method before storing the merged values from the end of the combined length.
Note also that you should use type size_t for the index and length variables, which is tricky as you cannot rely on negative values to detect end conditions. Careful implementation actually results in simpler code as shown below.
Here is a modified version:
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int>& nums1, size_t n, vector<int>& nums2, size_t m) {
size_t i = n, j = m, k = n + m;
if (nums1.size() < k) {
nums1.resize(k);
}
while (i > 0 && j > 0) {
if (nums1[i - 1] < nums2[j - 1]) {
nums1[--k] = nums2[--j];
} else {
nums1[--k] = nums1[--i];
}
}
while (j > 0) {
nums1[--k] = nums2[--j];
}
}
int main() {
vector<int> a = { 1, 3, 5, 7 };
vector<int> b = { 0, 2, 4, 6, 8, 10 };
merge(a, a.size(), b, b.size());
for (size_t i = 0; i < a.size(); i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}

I'm having trouble formatting the print statement using a nested for loop

I am taking hard coded information of two arrays and creating the Union, Intersection and Difference of them.
My issue is that I can't get the Intersection or Difference to print with the right format.
I have tried a different variety of while loops with for and if statements, but can't quite get it. I know I'm close-ish. (Hopefully)
Main information:
int setA[] = {3,4,9,12,13,15};
int setB[] = {1,3,5,7,9};
int lenA = sizeof(setA) / sizeof(setA[0]);
int lenB = sizeof(setB) / sizeof(setB[0]);
Difference(setA, setB, lenA, lenB);
Intersection(setA, setB, lenA, lenB);
void Intersection(int setA[], int setB[], int lenA, int lenB)
{
cout << "AnB = {";
for (int i = 0; i < lenA; i++)
{
for (int j = 0; j < lenB; j++)
{
while(setA[i] == setB[j] && i < lenA - 1)
{
cout << setA[i++] << ", ";
}
if(i < lenA && setA[i] == setB[j])
{
cout << setA[i++];
}
}
}
cout << "}";
cout << endl;
}
void Difference(int setA[], int setB[], int lenA, int lenB)
{
cout << "A - B = {";
for (int i = 0; i < lenA; i++)
{
bool comp = false;
for (int j = 0; j < lenB; j++)
if (setA[i] == setB[j])
{
comp = true;
break;
}
if(!comp)
{
cout << setA[i] << ",";
}
}
cout << "}";
cout << endl;
}
I want the output to look like:
AnB = {3, 9} (Intersection)
A-B = {4, 12, 13, 15} (Difference)
What I am getting:
AnB = {3, 9, } (Intersection)
A-B = {4, 12, 13, 15, } (Difference)
I just need to get the commas at the end fixed, but don't know how.
Sorry if this question is way too long, I wasn't sure of how to get my issue out.

Why is this triggering a breakpoint?

I have looked extensively for the problem in this code, but I can't seem to figure out what tragic error I made and why it is triggering a breakpoint.
(After 3 or 4 inputs, it triggers and I don't know why it doesn't trigger at the start or what is causing it)
#include <conio.h> // For function getch()
#include <cstdlib> // For several general-purpose functions
#include <fstream> // For file handling
#include <iomanip> // For formatted output
#include <iostream> // For cin, cout, and system
#include <string> // For string data type
using namespace std; // So "std::cout" may be abbreviated to "cout", for example.
string convertDecToBin(int dec)
{
int *arrayHex, arraySize = 0;
arrayHex = new int[];
string s = " ";
int r = dec;
for (int i = 0; r != 0; i++)
{
arrayHex[i] = r % 2;
r = r / 2;
arraySize++;
}
for (int j = 0; j < arraySize; j++)
{
s = s + to_string(arrayHex[arraySize - 1 - j]);
}
delete[] arrayHex;
return s;
}
string convertDecToOct(int dec)
{
int *arrayHex, arraySize = 0;
arrayHex = new int[];
string s = " ";
int r = dec;
for (int i = 0; r != 0; i++)
{
arrayHex[i] = r % 8;
r = r / 8;
arraySize++;
}
for (int j = 0; j < arraySize; j++)
{
s = s + to_string(arrayHex[arraySize - 1 - j]);
}
delete[] arrayHex;
return s;
}
int main()
{
int input = 0;
while (input != -1)
{
cout << "\nEnter a decimal number (-1 to exit loop): ";
cin >> input;
if (input != -1)
{
cout << "Your decimal number in binary expansion: " << convertDecToBin(input);
cout << "\nYour decimal number in octal ecpression: " << convertDecToOct(input);
}
}
cout << "\n\nPress any key to exit. . .";
_getch();
return 0;
}
arrayHex = new int[] is your problem - C\C++ does not support dynamic sizing arrays. You need to specify a size for the array to allocation, otherwise you'll get memory block overruns.

C++ Function is not returning a value

here is my code, I can not figure out why it won't work as a function when the exact code in main() produces the correct answer. The assignment is to convert binary number to decimal.
#include <iostream>
#include <cstdlib>
#include "std_lib_facilities.h"
using namespace std;
int binaryCon(int biNum);
int main()
{
int num, bin, Bnum;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
Bnum = binaryCon(num);
cout << "The decimal equivalent of " << bin << " : " << Bnum << endl;
}
int binaryCon(int biNum)
{
long dec = 0, rem = 0, base = 1;
enter code here`while (biNum > 0)
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
return biNum;
}
corrected code:
#include <iostream>
#include <cstdlib>
using namespace std;
int binaryCon(int biNum);
int main()
{
int num, bin, Bnum;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
Bnum = binaryCon(num);
cout << "The decimal equivalent of " << bin << " : " << Bnum << endl;
getchar();
return 0;
}
int binaryCon(int biNum)
{
long dec = 0, rem = 0, base = 1;
while (biNum > 0){
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}
return dec;
}
As you are not using { and } in your while loop may be its going in infinite loop. As its working for this line only
while (biNum > 0)
rem = biNum % 10; // running this line infinite as `biNum > 0`
Use
while (biNum > 0){
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}
maybe this?
while (biNum > 0)
{
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}
int main() or int main(int argc, char** argv) must return a value. If you return 0 then it means that there is no problem with code. Another numbers 1,2 etc means there is an error.(Returned numbers are error numbers)

How to solve http://www.spoj.com/problems/MST1/ in n is 10^9

Using Bottom to up DP approach, I am able to solve the problem How to solve http://www.spoj.com/problems/MST1/ upto 10^8.
If input is very large n upto 10^9. I will not be able to create lookup table for upto 10^9. So what will be better approach to solve the problem ?
Is there any heuristic solution ?
#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
int main()
{
const int N_MAX = 20000001;
int *DP = new int[N_MAX];
DP[1] = 0;
for (int i = 2; i < N_MAX; i++) {
int minimum = DP[i - 1];
if (i % 3 == 0) minimum = min(minimum, DP[i/3]);
if (i % 2 == 0) minimum = min(minimum, DP[i/2]);
DP[i] = minimum + 1;
}
int T, N; cin >> T;
int c = 1;
while (T--) {
cin >> N;
cout << "Case " << c++ << ": " << DP[N] << endl;
}
delete[] DP;
}

Resources