Go to the documentation of this file.00001
00008
00009
00010
00011
00012 #include <ecl/config.hpp>
00013
00014
00015
00016
00017
00018 #include <iostream>
00019 #include <vector>
00020 #include "../../include/ecl/threads/mutex.hpp"
00021 #include "../../include/ecl/threads/thread.hpp"
00022 #include <ecl/time/sleep.hpp>
00023
00024 int shared_value = 0;
00025 ecl::Mutex mutex;
00026
00027 void f() {
00028 ecl::Sleep sleep;
00029 sleep(1);
00030
00031 std::cout << "Thread: enter blocking" << std::endl;
00032 mutex.lock();
00033
00034 shared_value = 10;
00035 std::cout << "Thread: sets shared_value to 10" << std::endl;
00036
00037 mutex.unlock();
00038 std::cout << "Thread: leave blocking" << std::endl;
00039 }
00040
00041 int main() {
00042
00043 std::cout << std::endl;
00044 std::cout << "***********************************************************" << std::endl;
00045 std::cout << " Mutex" << std::endl;
00046 std::cout << "***********************************************************" << std::endl;
00047 std::cout << std::endl;
00048
00049 std::cout << "Lock" << std::endl;
00050 mutex.lock();
00051
00052 std::cout << "Unlock" << std::endl;
00053 mutex.unlock();
00054
00055 std::cout << "Trylock" << std::endl;
00056 mutex.trylock();
00057
00058 std::cout << "Try to lock block already locked" << std::endl;
00059 if (mutex.trylock()) {
00060 std::cout << "Abnormal" << std::endl;
00061 } else {
00062 std::cout << "Failed(Normal)" << std::endl;
00063 }
00064
00065 std::cout << "Unlock" << std::endl;
00066 mutex.unlock();
00067
00068 std::cout << std::endl;
00069 std::cout << "***********************************************************" << std::endl;
00070 std::cout << " Synchronization" << std::endl;
00071 std::cout << "***********************************************************" << std::endl;
00072 std::cout << std::endl;
00073
00074 ecl::Thread thread_f(f);
00075 ecl::Sleep sleep;
00076
00077 std::cout << "Main: enter blocking" << std::endl;
00078 mutex.lock();
00079 sleep(3);
00080
00081 if (shared_value < 5) {
00082 std::cout << "shared_value(" << shared_value << ") is smaller than 5" << std::endl;
00083 } else {
00084 std::cout << "shared_value(" << shared_value << ") is larger than 5" << std::endl;
00085 }
00086
00087 mutex.unlock();
00088 std::cout << "Main: leave blocking" << std::endl;
00089
00090 thread_f.join();
00091
00092 std::cout << std::endl;
00093 std::cout << "***********************************************************" << std::endl;
00094 std::cout << " Passed" << std::endl;
00095 std::cout << "***********************************************************" << std::endl;
00096 std::cout << std::endl;
00097
00098 return 0;
00099 }