#include <iostream> #include <string> #include <thread> #include <mutex>
using namespace std;
int com_i; mutex mut;
void myThread() { ?? ?while (1) ?? ?{ ?? ??? ?unique_lock<mutex> sbguard1(mut,try_to_lock);
?? ??? ?if (sbguard1.owns_lock()) ?? ??? ?{ ?? ??? ??? ?cout << com_i++ << "..............................." << endl; ?? ??? ??? ?if (com_i > 1000) ?? ??? ??? ??? ?com_i = 0; ?? ??? ??? ?chrono::milliseconds dura(1000); ?? ??? ??? ?this_thread::sleep_for(dura); ?? ??? ?} ?? ??? ?else ?? ??? ?{ ?? ??? ??? ?cout << "lock failed................................"<<endl; ?? ??? ??? ?chrono::milliseconds dura(300); ?? ??? ??? ?this_thread::sleep_for(dura); ?? ??? ?} ?? ?} }
int main() { ?? ?cout << "test" << endl; ?? ?com_i = 0; ?? ?thread t1(myThread); ?? ?thread t2(myThread); ?? ?t1.join(); ?? ?t2.join(); }
|