Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<thread>
- #include<ctime>
- #include<mutex>
- #include<bits/stdc++.h>
- //
- //https://www.youtube.com/watch?v=13dFggo4t_I&list=PL5jc9xFGsL8E12so1wlMS0r0hTQoJL74M&index=6
- //
- using namespace std;
- mutex carMutex;
- mutex mux;
- void function1(char symbol){
- carMutex.lock();
- for(int i=0;i<200;i++){
- cout << symbol;
- }
- carMutex.unlock();
- }
- void function2(){
- unique_lock<mutex> carLock(carMutex);
- carLock.try_lock();
- carLock.try_lock_for(500ns);
- for(int i=0;i<200;i++){
- cout << "- ";
- }
- this_thread::sleep_for(2000ms);
- this_thread::get_id();
- carLock.unlock();
- }
- void func3(){
- // automatically unlocks when variable goes out of scope
- lock_guard<mutex> guardLock(mux);
- cout << "Hello" <<endl;
- }
- int main(){
- time_t currentTime = time(nullptr);
- cout << currentTime << endl;
- thread worker1(function1, ')');
- thread worker2(function2);
- if(worker1.joinable()){
- worker1.join();
- }
- // shifting ownership of thread
- thread t3 = move(worker1);
- worker2.detach();
- // returns no of cores in system, optimal -> no of threads = no of cores
- hardware_concurrency();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement