void customer() { std::unique_lock<std::mutex> graud(mut); if(mut.try_lock()) { std::cout << "mutex unlocked after unique_lock" <<std::endl; }else{ std::cout <<"mutex locked after unique_lock" <<std::endl; } while(flag == 0) { std::cout << "wait........." <<std::endl; cond.wait(graud); } if(mut.try_lock()) { std::cout << "mutex unlocked after wait" <<std::endl; }else{ std::cout <<"mutex locked after wait" <<std::endl; } std::cout << "flag = " << flag << std::endl; }
void f() { time_point t0 = Clock::now(); assert(!m.try_lock()); assert(!m.try_lock()); assert(!m.try_lock()); while(!m.try_lock()) ; time_point t1 = Clock::now(); m.unlock(); ns d = t1 - t0 - ms(250); assert(d < ns(50000000)); // within 50ms }
/** * To remove from the list, we need to keep a pointer to the previous * node, too. Note that this is much easier on account of us having a * sentinel */ void remove(int val) { while (true) { if (linkMtx.try_lock()) { // find the node whose val matches the request Node* prev = sentinel; Node* curr = prev->next; while (curr != NULL) { // if we find the node, disconnect it and end the search if (curr->val == val) { prev->next = curr->next; // delete curr... free(curr); break; } else if (curr->val > val) { // this means the search failed break; } // advance one node prev = curr; curr = prev->next; } linkMtx.unlock(); return; } } }
void deliver_new_event(std::size_t, const void* inbnd) { #ifndef NDEBUG bool success = assert_single_threaded.try_lock(); assert(success); AtScopeEnd ase{[&]{assert_single_threaded.unlock();}}; #endif //std::cout << "received message" << std::endl; if (on_first_message){ //std::cout << "expected this message is size_t" << std::endl; recv.first = *((int*)(inbnd)); on_first_message = false; event_fd.notify(); //async_tick(c); } else{ //std::cout << "expected this message is vector" << std::endl; recv.second = from_bytes<std::vector<unsigned char> >(nullptr,((char*) inbnd)); { stringstream ss; ss << "received " << recv.second->size() << " element vector" << std::endl; //std::cout << ss.str(); } on_first_message = true; event_fd.notify(); //async_tick(c); } }
/** * insert method; find the right place in the list, add val so that it is * in sorted order; if val is already in the list, exit without inserting */ void insert(int val) { while (true) { if (linkMtx.try_lock()) { // traverse the list to find the insertion point Node* prev =sentinel; Node* curr = prev->next; while (curr != NULL) { if (curr->val >= val) break; prev = curr; curr = prev->next; } // now insert new_node between prev and curr // // NB: if the test fails, it means we quit the above loop on account // of /finding/ val, in which case we just exit if (!curr || ((curr->val) > val)) { // create the new node Node* i = (Node*)malloc(sizeof(Node)); i->val = val; i->next = curr; // insert it prev->next = i; } linkMtx.unlock(); return; } } }
void attempt_10k_incresses() { for (auto i = 0; i < 10000; ++i) if (mtx.try_lock()) { // only increase if currently not locked ++counter; mtx.unlock(); } }
void SimulateClient(InternetCafe* internetCafe, std::vector<Client*>& clients, unsigned int clientId, std::mutex& mtx) { Client* curClient = nullptr; curClient = clients[clientId]; bool clientIsRunning = true; if (curClient) { while (clientIsRunning) { if (mtx.try_lock()) { if (internetCafe->RequestComputer(curClient->GetId(), curClient->GetMoney(), clientIsRunning)) { curClient->SetMoney(curClient->GetMoney() - internetCafe->GetHireCost()); } mtx.unlock(); } std::this_thread::sleep_for(std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::duration<double, std::ratio<1, 1000>>(TIMESTEP))); } std::cout << "User " << curClient->GetId() << " has exited simulation" << std::endl; } }
// the main device method virtual void run() { if(!opened) { scene->addItem(item); // lock the image viewer img_view_mutex.lock(); // update the pixmap and unlock the image viewer show_image(); // open a window to show the QGraphicsScene view->show(); // set the flag to true opened = true; } else { if (img_view_mutex.try_lock()) { // a new thread! std::thread show_image_thread(&ImageViewerDevice::show_image, this); // leave it alone show_image_thread.detach(); } } }
/** * I hope everyone come inside, and everyone know * how many had been here */ int wait_for_all_entering_ep() { static std::atomic<bool> wait_finish; static std::atomic<int> thread_inside_count; static std::atomic<int> saved_thread_inside_count; static std::mutex mtx; wait_finish = false; thread_inside_count++; if (mtx.try_lock()) { while (thread_inside_count != get_expected_thread_count()) { // Well, furiosly infinit looping until all the threads runnin in the // kernel are trapped here } saved_thread_inside_count = thread_inside_count.load(); wait_finish = true; mtx.unlock(); } else { while (wait_finish == false); } thread_inside_count--; return saved_thread_inside_count.load(); }
bool try_lock() { check_for_hierarchy_violation(); if(!internal_mutex.try_lock()) return false; update_hierarchy_value(); return true; }
void attempt_10k_inc() { for (int i=0; i<10000; ++i) { if (mtx.try_lock()) { // only increase if lock can be got successfully ++counter; mtx.unlock(); } } }
void ConnectOnInput(int wiimote_number) { if (!g_wiimotes_mutex.try_lock()) return; if (g_wiimotes[wiimote_number]) g_wiimotes[wiimote_number]->ConnectOnInput(); g_wiimotes_mutex.unlock(); }
bool try_lock() { if (_mutex.try_lock()) { _isLocked = true; return true; } else { _isLocked = false; return false; } };
void iDroneFSM() { while (run) { if (navLock.try_lock()) { fsm.act(model); navLock.unlock(); } //std::this_thread::sleep_for(std::chrono::seconds(2)); } }
void threadfunction_mutex_try_lock(int arg) { long long count = 0; while(true) { if(coutLock.try_lock()) { cout << "mutex try_lock: " << arg << ", this_thread::get_id=" << this_thread::get_id() << ", tried " << count << " times before we attained the lock" << "\n"; coutLock.unlock(); break; } else { // lock is busy, do something else. Let's count the number of times we tried. count++; } } }
void thread_function_increase() { for (int i=0; i<3; i++) { if(g_counter_mutex.try_lock()) //g_counter_mutex.lock(); { ++g_counter; cout << this_thread::get_id() << ": " << i << endl; g_counter_mutex.unlock(); this_thread::sleep_for(std::chrono::seconds(2)); } } }
void CBaLog::logRoutine(TBaCoreThreadArg *pArg) { while (!sLogdArg.exitTh) { // Crate and delete have preference to avoid deadlocks. // deleting a logger flushed it anyways if (sMtx.try_lock()) { // iterate loggers for (auto &kv : sLoggers) { kv.second->Flush(); } sMtx.unlock(); } BaCoreMSleep(50); } }
void func(size_t thread_index, tree_mutex *m) { size_t n = 10000; //dbg(thread_index, n); while (n--) { m->lock(thread_index); assert(m2.try_lock()); ++i; ++ai; ++ai2; m2.unlock(); m->unlock(thread_index); } }
void manage_func() { while (!g_finish) { if (g_mtx.try_lock()) { if (expected_thread_count != MAX_THREAD_COUNT) { expected_thread_count--; } g_mtx.unlock(); } std::this_thread::yield(); } }
void notify_each_run() { // sometimes, we just random to set the thread count to the expected value // to increase the possibility to somewhat racing condition if (g_mtx.try_lock()) { if (random() % 88 > 44) { expected_thread_count = MAX_THREAD_COUNT * 2; } else { expected_thread_count = MAX_THREAD_COUNT; } g_mtx.unlock(); } }
// Read the Wiimote once void Update(int wiimote_number) { // Try to get a lock and return without doing anything if we fail // This avoids blocking the CPU thread if (!g_wiimotes_mutex.try_lock()) return; if (g_wiimotes[wiimote_number]) g_wiimotes[wiimote_number]->Update(); // Wiimote::Update() may remove the Wiimote if it was disconnected. if (!g_wiimotes[wiimote_number]) { Host_ConnectWiimote(wiimote_number, false); } g_wiimotes_mutex.unlock(); }
/** * lookup method: just traverse the list in order, and see if we find the * val */ bool lookup(int val) { while (true) { if (linkMtx.try_lock()) { Node* curr = sentinel->next; while (curr != NULL) { if (curr->val >= val) break; curr = curr->next; } bool result = ((curr != NULL) && (curr->val == val)); linkMtx.unlock(); return result; } } }
bool try_put(messageT msg) { // Try to put a single message into the mailbox if( queue_mutex.try_lock() ) { // Push message into mailbox messages.push(msg); // Signal there is a message in the mailbox msg_available_cv.notify_one(); // Unlock queue queue_mutex.unlock(); return true; } // Otherwise, say mailbox is unavailable else return false; }
bool ProxygenServer::sniNoMatchHandler(const char *server_name) { try { if (!RuntimeOption::SSLCertificateDir.empty()) { static std::mutex dynLoadMutex; if (!dynLoadMutex.try_lock()) return false; SCOPE_EXIT { dynLoadMutex.unlock(); }; // Reload all certs. Logger::Warning("Reloading SSL certificates upon server name %s", server_name); ServerNameIndication::load(RuntimeOption::SSLCertificateDir, std::bind(&ProxygenServer::dynamicCertHandler, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); return true; } } catch (const std::exception &ex) { Logger::Error("Failed to reload certificate files or key files"); } return false; }
void ImageLoader::UpdateTextures() { if (PendingUploads.size() && LoadMutex.try_lock()) { for (auto i = PendingUploads.begin(); i != PendingUploads.end(); i++) { ImageData imgData; imgData.Data = i->second.Data; imgData.Width = i->second.Width; imgData.Height = i->second.Height; Image::LastBound = InsertImage(i->first, &imgData); free(imgData.Data); } PendingUploads.clear(); LoadMutex.unlock(); } if (Textures.size()) { for (auto i = Textures.begin(); i != Textures.end();) { if (i->second->IsValid) /* all of them are valid */ break; if (Load(i->first) == nullptr) // If we failed loading it no need to try every. single. time. { i = Textures.erase(i); continue; } ++i; } } }
int __cdecl HandleCrash(PEXCEPTION_POINTERS pExceptPtrs) { /* only allow one thread to crash. */ if(!m_crashLock.try_lock()) { TerminateThread(GetCurrentThread(), static_cast<DWORD>(-1)); return EXCEPTION_EXECUTE_HANDLER; } // Create the date/time string tm pTime; time_t curtime = time(NULL); localtime_s(&pTime, &curtime); char filename[MAX_PATH]; TCHAR modname[MAX_PATH*2]; ZeroMemory(filename, sizeof(filename)); ZeroMemory(modname, sizeof(modname)); if(GetModuleFileName(0, modname, MAX_PATH*2-2) <= 0) { strcpy_s(modname, "UNKNOWN"); } char * mname = strrchr(modname, '\\'); (void*)mname++; // Remove the last sprintf_s(filename, "CrashDumps\\dump-%s-%u-%u-%u-%u-%u-%u-%u.dmp", mname, pTime.tm_year+1900, pTime.tm_mon, pTime.tm_mday, pTime.tm_hour, pTime.tm_min, pTime.tm_sec, GetCurrentThreadId()); HANDLE hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0); if(hDump == INVALID_HANDLE_VALUE) { // Create the directory first CreateDirectory("CrashDumps", 0); hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0); } //PrintCrashInformation(pExceptPtrs); //printf_s("\nCreating crash dump file %s\n", filename); if(hDump == INVALID_HANDLE_VALUE) { //MessageBox(0, "Could not open crash dump file.", "Crash dump error.", MB_OK); } else { MINIDUMP_EXCEPTION_INFORMATION info; info.ClientPointers = FALSE; info.ExceptionPointers = pExceptPtrs; info.ThreadId = GetCurrentThreadId(); MINIDUMP_TYPE mdt = (MINIDUMP_TYPE)(MiniDumpWithFullMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithThreadInfo | MiniDumpWithHandleData); MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDump, mdt, (pExceptPtrs != NULL) ? &info : 0, 0, 0); CloseHandle(hDump); } m_crashLock.unlock(); return EXCEPTION_EXECUTE_HANDLER; }
decltype (auto) try_lock() { return mut.try_lock(); }
inline bool lock() { return m_lock.try_lock(); }