142 lines
2.7 KiB
C++
142 lines
2.7 KiB
C++
#include <iostream>
|
|
#include <thread>
|
|
#include <mutex>
|
|
#include "Semaphore.h"
|
|
#include <process.h>
|
|
|
|
using namespace std;
|
|
|
|
// Thread T1 - Schreibt alle Kleinbuchstaben des Alphabets
|
|
void thread1() {
|
|
for (char c = 'a'; c <= 'z'; ++c) {
|
|
cout << c << ' ';
|
|
}
|
|
cout << endl;
|
|
}
|
|
|
|
// Thread T2 - Schreibt alle natürlichen Zahlen von 0 bis 32
|
|
void thread2() {
|
|
for (int i = 0; i <= 32; ++i) {
|
|
cout << i << ' ';
|
|
}
|
|
cout << endl;
|
|
}
|
|
|
|
// Thread T3 - Schreibt alle Großbuchstaben des Alphabets
|
|
void thread3() {
|
|
for (char c = 'A'; c <= 'Z'; ++c) {
|
|
cout << c << ' ';
|
|
}
|
|
cout << endl;
|
|
}
|
|
|
|
void asynch_init(){
|
|
// Start der Threads
|
|
thread t1(thread1);
|
|
thread t2(thread2);
|
|
thread t3(thread3);
|
|
|
|
// Warten auf die Beendigung der Threads
|
|
t1.join();
|
|
t2.join();
|
|
t3.join();
|
|
}
|
|
|
|
mutex mtx;
|
|
|
|
void mutexThread1() {
|
|
mtx.lock();
|
|
|
|
for (char ch = 'a'; ch <= 'z'; ch++) {
|
|
cout << ch << " ";
|
|
}
|
|
cout << endl;
|
|
|
|
mtx.unlock();
|
|
}
|
|
|
|
void mutexThread2() {
|
|
|
|
mtx.lock();
|
|
|
|
for (int i = 0; i < 33; i++) {
|
|
cout << i << " ";
|
|
}
|
|
cout << endl;
|
|
|
|
mtx.unlock();
|
|
}
|
|
|
|
void mutexThread3() {
|
|
mtx.lock();
|
|
|
|
for (char ch = 'A'; ch <= 'Z'; ch++) {
|
|
cout << ch << " ";
|
|
}
|
|
cout << endl;
|
|
|
|
mtx.unlock();
|
|
}
|
|
|
|
void mutex_init() {
|
|
thread t1(mutexThread1); // mutexThread1 is running
|
|
thread t2(mutexThread2); // mutexThread2 is running
|
|
thread t3(mutexThread3); // mutexThread3 is running
|
|
t1.join(); // main thread waits for t1 to finish
|
|
t2.join(); // main thread waits for t2 to finish
|
|
t3.join(); // main thread waits for t3 to finish
|
|
}
|
|
|
|
Semaphore semaphore;
|
|
|
|
void semaphoreThread1() {
|
|
semaphore.wait();
|
|
for (char ch = 'a'; ch <= 'z'; ch++) {
|
|
cout << ch << " ";
|
|
}
|
|
cout << endl;
|
|
semaphore.post();
|
|
}
|
|
|
|
void semaphoreThread2() {
|
|
semaphore.wait();
|
|
for (int i = 0; i < 33; i++) {
|
|
cout << i << " ";
|
|
}
|
|
cout << endl;
|
|
semaphore.post();
|
|
|
|
}
|
|
|
|
void semaphoreThread3() {
|
|
semaphore.wait();
|
|
for (char ch = 'A'; ch <= 'Z'; ch++) {
|
|
cout << ch << " ";
|
|
}
|
|
cout << endl;
|
|
semaphore.post();
|
|
|
|
}
|
|
|
|
void semaphore_init() {
|
|
thread t1(semaphoreThread1); // thread1 is running
|
|
thread t2(semaphoreThread2); // thread2 is running
|
|
thread t3(semaphoreThread3); // thread3 is running
|
|
t1.join(); // main thread waits for t1 to finish
|
|
t2.join(); // main thread waits for t2 to finish
|
|
t3.join(); // main thread waits for t3 to finish
|
|
}
|
|
|
|
int main() {
|
|
|
|
cout << "Asynch" << endl;
|
|
asynch_init();
|
|
|
|
cout << "Mutex" << endl;
|
|
mutex_init();
|
|
|
|
cout << "Semaphore" << endl;
|
|
semaphore_init();
|
|
|
|
return 0;
|
|
} |