Unit 4- Threads_Program Solution
Unit 4- Threads_Program Solution
void printEven() {
for (int i = 1; i <= 20; ++i) {
if (i % 2 == 0)
std::cout << "Even: " << i << std::endl;
}
}
void printOdd() {
for (int i = 1; i <= 20; ++i) {
if (i % 2 != 0)
std::cout << "Odd: " << i << std::endl;
}
}
int main() {
// Create two threads
std::thread t1(printEven);
std::thread t2(printOdd);
#include <iostream>
#include <thread>
class Countdown {
public:
void operator()() {
for (int i = 10; i >= 1; --i) {
std::cout << "Countdown: " << i << std::endl;
}
}
};
int main() {
Countdown count;
std::thread t(count);
t.join();
std::cout
#include <iostream>
#include <thread>
#include <chrono>
class Countdown {
public:
void operator()() {
for (int i = 10; i >= 1; --i) {
std::cout << "Countdown: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
};
class Countup {
public:
void operator()() {
for (int i = 1; i <= 10; ++i) {
std::cout << "Countup: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
};
int main() {
Countdown down;
Countup up;
std::thread t1(down); // Thread for countdown
std::thread t2(up); // Thread for countup
t1.join();
t2.join();
#include <iostream>
#include <thread>
int main() {
auto printSquares = []() {
for (int i = 1; i <= 10; ++i) {
std::cout << "Square of " << i << " is " << (i * i) << std::endl;
}
};
std::thread t(printSquares);
t.join();
std::cout << "All squares printed.\n";
return 0;
}
int A[ROWS1][COLS1] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int B[ROWS2][COLS2] = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int main() {
if (COLS1 != ROWS2) {
std::cout << "Matrix multiplication not possible: incompatible
dimensions." << std::endl;
return 1;
}
std::thread threads[ROWS1];
return 0;
}
int i = 0, j = 0, k = low;
int main() {
std::cout << "Original array: ";
for (int i = 0; i < SIZE; ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
return 0;
}
// Swap function
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
// Quick Sort
void quickSort(int low, int high) {
if (low < high) {
int pivotIndex = partition(low, high);
quickSort(low, pivotIndex - 1);
quickSort(pivotIndex + 1, high);
}
}
// Manual merge of two sorted parts
void mergeTwoSortedParts(int start1, int end1, int start2, int end2) {
int n1 = end1 - start1 + 1;
int n2 = end2 - start2 + 1;
int* temp = new int[n1 + n2];
delete[] temp;
}
int main() {
std::cout << "Original array: ";
for (int i = 0; i < SIZE; ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
return 0;
}