void cmdVelReceived(const geometry_msgs::Twist::ConstPtr& cmd_vel) { std::cout << "cmdVel Received: speed = " << cmd_vel->linear.x << " angular = " << cmd_vel->angular.z << std::endl; if(bumper_warning.load()) roomba->drive(-0.2, 0); else if(ir_warning.load()) roomba->drive(0, cmd_vel->angular.z); else roomba->drive(cmd_vel->linear.x,cmd_vel->angular.z); }
void thread_pool::thread_func(std::atomic_bool & stop_request) { std::unique_lock<std::mutex> lk(m_mutex, std::defer_lock); for (;;) { ext::intrusive_ptr<task_base> task_ptr; lk.lock(); if (stop_request.load(std::memory_order_relaxed)) return; if (!m_tasks.empty()) goto avail; again: m_event.wait(lk); if (stop_request.load(std::memory_order_relaxed)) return; if (m_tasks.empty()) goto again; avail: task_ptr.reset(&m_tasks.front(), ext::noaddref); m_tasks.pop_front(); lk.unlock(); task_ptr->execute(); } }
// ------------------------------------------------------------------------ void addAndSetTime(uint32_t ping, uint64_t server_time) { if (m_synchronised.load() == true) return; if (m_force_set_timer.load() == true) { m_force_set_timer.store(false); m_synchronised.store(true); STKHost::get()->setNetworkTimer(server_time + (uint64_t)(ping / 2)); return; } const uint64_t cur_time = StkTime::getMonoTimeMs(); // Discard too close time compared to last ping // (due to resend when packet loss) // 10 packets per second as seen in STKHost const uint64_t frequency = (uint64_t)((1.0f / 10.0f) * 1000.0f) / 2; if (!m_times.empty() && cur_time - std::get<2>(m_times.back()) < frequency) return; // Take max 20 averaged samples from m_times, the next addAndGetTime // is used to determine that server_time if it's correct, if not // clear half in m_times until it's correct if (m_times.size() >= 20) { uint64_t sum = std::accumulate(m_times.begin(), m_times.end(), (uint64_t)0, [cur_time](const uint64_t previous, const std::tuple<uint32_t, uint64_t, uint64_t>& b)->uint64_t { return previous + (uint64_t)(std::get<0>(b) / 2) + std::get<1>(b) + cur_time - std::get<2>(b); }); const int64_t averaged_time = sum / 20; const int64_t server_time_now = server_time + (uint64_t)(ping / 2); int difference = (int)std::abs(averaged_time - server_time_now); if (std::abs(averaged_time - server_time_now) < UserConfigParams::m_timer_sync_difference_tolerance) { STKHost::get()->setNetworkTimer(averaged_time); m_times.clear(); m_force_set_timer.store(false); m_synchronised.store(true); Log::info("NetworkTimerSynchronizer", "Network " "timer synchronized, difference: %dms", difference); return; } m_times.erase(m_times.begin(), m_times.begin() + 10); } m_times.emplace_back(ping, server_time, cur_time); }
bool fiber_waiter::wait_ready(std::chrono::steady_clock::duration timeout_duration) noexcept { if (gth_thread_type == thread_type::thread) { std::unique_lock<std::mutex> lk(m_thread_mutex); return m_thread_var.wait_for(lk, timeout_duration, [this] { return m_ready.load(std::memory_order_relaxed); }); } else { std::unique_lock<boost::fibers::mutex> lk(m_fiber_mutex); return m_fiber_var.wait_for(lk, timeout_duration, [this] { return m_ready.load(std::memory_order_relaxed); }); } }
void fiber_waiter::wait_ready() noexcept { if (gth_thread_type == thread_type::thread) { std::unique_lock<std::mutex> lk(m_thread_mutex); return m_thread_var.wait(lk, [this] { return m_ready.load(std::memory_order_relaxed); }); } else { std::unique_lock<boost::fibers::mutex> lk(m_fiber_mutex); return m_fiber_var.wait(lk, [this] { return m_ready.load(std::memory_order_relaxed); }); } }
progressIndicatorThreadWrapper( const std::chrono::nanoseconds& updateInterval ) { m_stopCondition.store( false ); m_thread = std::thread( [this, &updateInterval] { FormattedPrint::On(std::cout, false).app(" "); int slashIndex = 0; while( ! m_stopCondition.load() ) { FormattedPrint::On(std::cout, false).app("\b\b\b \b") .color( Green ) .app('[') .color( Yellow ) .app( slashes[ slashIndex++ ] ) .color( Green ) .app(']') .color(); slashIndex = slashIndex % 4; std::this_thread::sleep_for( updateInterval ); } FormattedPrint::On(std::cout, false).app("\b\b\b"); }); }
void gstate_update_func() { POINT p; int mButton; if(GetSystemMetrics(SM_SWAPBUTTON)) mButton = VK_RBUTTON; // if swapped else mButton = VK_LBUTTON; // not swapped (normal) int screenWidth = GetSystemMetrics( SM_CXSCREEN ); int screenHeight = GetSystemMetrics( SM_CYSCREEN ); // default: SM_CX/CYSCREEN gets the size of a primary screen. // lines uncommented below are just for a specially need on multi-display. //int screenWidth = GetSystemMetrics( SM_CXVIRTUALSCREEN ); //int screenHeight = GetSystemMetrics( SM_CYVIRTUALSCREEN ); float r_screenWidth = 1.f / (float)(screenWidth -1); float r_screenHeight = 1.f / (float)(screenHeight -1); while ( inputThreadRunning.load( std::memory_order_relaxed ) ) { // "KeyState" is disabled for now, on Windows... //GetKey((long*)gstate->keys); GetCursorPos(&p); gMouseUGenGlobals.mouseX = (float)p.x * r_screenWidth; gMouseUGenGlobals.mouseY = 1.f - (float)p.y * r_screenHeight; gMouseUGenGlobals.mouseButton = (GetKeyState(mButton) < 0); std::this_thread::sleep_for( std::chrono::milliseconds( 17 ) ); } }
bool example1_rx(const std::string& dataaddress, unsigned short dataport, std::atomic_bool& stopFlag) { SuperBlock rxBlock; uint8_t rawBlock[sizeof(SuperBlock)]; int rawBlockSize; UDPSocket rxSocket(dataport); std::string senderaddress, senderaddress0; unsigned short senderport, senderport0 = 0; Example1Rx ex1(nbSamplesPerBlock, nbOriginalBlocks, nbRecoveryBlocks); std::cerr << "example1_rx: receiving on address: " << dataaddress << " port: " << (int) dataport << std::endl; while (!stopFlag.load()) { rawBlockSize = 0; while (rawBlockSize < sizeof(SuperBlock)) { rawBlockSize += rxSocket.RecvDataGram((void *) &rawBlock[rawBlockSize], (int) sizeof(SuperBlock), senderaddress, senderport); if ((senderaddress != senderaddress0) || (senderport != senderport0)) { std::cerr << "example1_rx: connected to: " << senderaddress << ":" << senderport << std::endl; senderaddress0 = senderaddress; senderport0 = senderport; } usleep(10); } rxBlock = *((SuperBlock *) rawBlock); ex1.processBlock(rxBlock); } }
void reader_thread() { while (!data_ready.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } std::cout<<"The answer = "<<data[0]<<"\n"; }
void consume(std::atomic_bool& done, int* array, int_queue& q) { while (!done.load()) { int val; if(q.pop(val)) { array[val] = val; } else { std::this_thread::yield(); } } // drain while (!q.empty()) { int val; if(q.pop(val)) { array[val] = val; } else { std::this_thread::yield(); } } }
/** * This is the actual function that the thread executes. * It receives a block from the scheduler, class its run() method and returns it to the scheduler. * The thread runs until the it is told to stop by setting the m_stop boolean flag */ void operator()() { if(CPU_COUNT(&m_mask)>0) { pthread_t id = pthread_self(); int ret = pthread_setaffinity_np(id, sizeof(m_mask), &m_mask); if(ret != 0) { perror("setaffinity"); throw(std::runtime_error("set affinity failed")); } } while(!m_stop.load()) { std::shared_ptr<Block>torun(m_scheduler.next_task(m_id)); if(torun) { torun->run(); m_scheduler.task_done(m_id, std::move(torun)); } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } m_stop.store(false); }
static void run(std::atomic_bool& running, int fd, felix::netio::DataSinkCallbacks* callbacks) { while(running.load()) { /* felix::netio::msgheader header; ssize_t count = read(fd, &header, sizeof(header)); assert(count == sizeof(header)); char* data = new char[header.len]; ssize_t bytes_read = 0; while(bytes_read < header.len) { count = read(fd, data+bytes_read, header.len-bytes_read); if (count == 0) { std::vector<felix::netio::DataSinkMessage> messages; messages.emplace_back(data, bytes_read); callbacks->on_data_received_with_error(messages); return; } bytes_read += count; } */ char* data = new char[1024]; ssize_t count = read(fd, data, 1024); std::vector<felix::netio::DataSinkMessage> messages; messages.emplace_back(data, count); callbacks->on_data_received(messages); } }
static void stepCore(uint32_t coreId, bool stepOver) { decaf_check(sIsPaused.load()); const cpu::CoreRegs *state = sCorePauseState[coreId]; uint32_t nextInstr = calculateNextInstr(state, stepOver); cpu::addBreakpoint(nextInstr, cpu::SYSTEM_BPFLAG); resumeAll(); }
void handleDbgBreakInterrupt() { // If we are not initialised, we should ignore DbgBreaks if (!decaf::config::debugger::enabled) { return; } std::unique_lock<std::mutex> lock(sMutex); auto coreId = cpu::this_core::id(); // Store our core state before we flip isPaused sCorePauseState[coreId] = cpu::this_core::state(); // Check to see if we were the last core to join on the fun auto coreBit = 1 << coreId; auto isPausing = sIsPausing.fetch_or(coreBit); if (isPausing == 0) { // This is the first core to hit a breakpoint sPauseInitiatorCoreId = coreId; // Signal the rest of the cores to stop for (auto i = 0; i < 3; ++i) { cpu::interrupt(i, cpu::DBGBREAK_INTERRUPT); } } if ((isPausing | coreBit) == (1 | 2 | 4)) { // This was the last core to join. sIsPaused.store(true); sIsPausing.store(0); sIsResuming.store(0); } // Spin around the release condition while we are paused while (sIsPausing.load() || sIsPaused.load()) { sPauseReleaseCond.wait(lock); } // Clear any additional DbgBreaks that occured cpu::this_core::clearInterrupt(cpu::DBGBREAK_INTERRUPT); // Everyone needs to leave at once in case new breakpoints occur. if ((sIsResuming.fetch_or(coreBit) | coreBit) == (1 | 2 | 4)) { sPauseReleaseCond.notify_all(); } else { while ((sIsResuming.load() | coreBit) != (1 | 2 | 4)) { sPauseReleaseCond.wait(lock); } } }
void thread_recv() { while (connected.load()) { spmsg_t msg = std::make_shared<msg_t>(sizeof(uint32_t)); if (!_do_recv(msg->data(), sizeof(uint32_t))) return; uint32_t msg_len = *(uint32_t*)msg->data(); msg->resize(msg_len + sizeof(uint32_t)); *(uint32_t*)msg->data() = msg_len; if (!_do_recv(msg->data() + sizeof(uint32_t), msg_len)) return; recv_queue.push(std::move(msg)); } }
/** * Main thread entry point for the IPC thread. * * This thread represents the IOS side of the IPC mechanism. * * Responsible for receiving IPC requests and dispatching them to the * correct IOS device. */ void ipcThreadEntry() { std::unique_lock<std::mutex> lock { sIpcMutex }; while (true) { if (!sIpcRequests.empty()) { auto request = sIpcRequests.front(); sIpcRequests.pop(); lock.unlock(); iosDispatchIpcRequest(request); lock.lock(); switch (request->cpuId) { case IOSCpuId::PPC0: sIpcResponses[0].push(request); cpu::interrupt(0, cpu::IPC_INTERRUPT); break; case IOSCpuId::PPC1: sIpcResponses[1].push(request); cpu::interrupt(1, cpu::IPC_INTERRUPT); break; case IOSCpuId::PPC2: sIpcResponses[2].push(request); cpu::interrupt(2, cpu::IPC_INTERRUPT); break; default: decaf_abort("Unexpected cpu id"); } } if (!sIpcThreadRunning.load()) { break; } if (sIpcRequests.empty()) { sIpcCond.wait(lock); } } sIpcThreadRunning.store(false); }
void gstate_update_func() { Window r; struct timespec requested_time , remaining_time; // NOTE: should not be required as this is the only thread accessing the x11 API // but omitting seems to cause troubles. XInitThreads(); d = XOpenDisplay ( NULL ); if (!d) return; Window rep_root, rep_child; XWindowAttributes attributes; int rep_rootx, rep_rooty ; unsigned int rep_mask; int dx, dy; float r_width; float r_height; r = DefaultRootWindow ( d ); XGetWindowAttributes ( d, r, &attributes ); r_width = 1.0 / (float)attributes.width; r_height = 1.0 / (float)attributes.height; while ( inputThreadRunning.load( std::memory_order_relaxed ) ) { XQueryKeymap ( d , (char *) (gKeyStateGlobals.keys) ); XQueryPointer ( d, r, &rep_root, &rep_child, &rep_rootx, &rep_rooty, &dx, &dy, &rep_mask); gMouseUGenGlobals.mouseX = (float)dx * r_width; gMouseUGenGlobals.mouseY = 1.f - ( (float)dy * r_height ); gMouseUGenGlobals.mouseButton = (bool) ( rep_mask & Button1Mask ); std::this_thread::sleep_for( std::chrono::milliseconds( 17 ) ); } }
void thread_send() { while (connected.load()) { spmsg_t msg; send_queue.pop(msg, true); if (!msg) continue; const char* buffer = (const char*)msg->data(); uint32_t remain = msg->size(); uint32_t len = 0; uint32_t pos = 0; do { len = ::send(this->sock, buffer+pos, remain, 0); if (len <= 0) { printf("send error %d\n", get_errno()); return; } pos += len; remain -= len; } while (remain > 0); } }
void MsgPopThread::run () { while (!ShouldStop_.load (std::memory_order_relaxed)) { const auto msg = gst_bus_timed_pop (Bus_, Multiplier_ * GST_SECOND); if (!msg) continue; QMetaObject::invokeMethod (SourceObj_, "handleMessage", Qt::QueuedConnection, Q_ARG (GstMessage_ptr, std::shared_ptr<GstMessage> (msg, gst_message_unref))); if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_ERROR) { BusDrainMutex_.lock (); BusDrainWC_.wait (&BusDrainMutex_); BusDrainMutex_.unlock (); qDebug () << "bus drained, continuing"; } } }
bool example1_tx(const std::string& dataaddress, int dataport, std::vector<int> &blockExclusionList, std::atomic_bool& stopFlag) { SuperBlock txBlocks[256]; Example1Tx ex1(nbSamplesPerBlock, nbOriginalBlocks, nbRecoveryBlocks); std::cerr << "example1_tx: transmitting on address: " << dataaddress << " port: " << dataport << std::endl; for (uint16_t frameNumber = 0; !stopFlag.load(); frameNumber++) { ex1.makeDataBlocks(txBlocks, frameNumber); if (!ex1.makeFecBlocks(txBlocks, frameNumber)) { std::cerr << "example1_tx: encode error" << std::endl; break; } ex1.transmitBlocks(txBlocks, dataaddress, dataport, blockExclusionList, 300); std::cerr << "."; } return true; }
// ------------------------------------------------------------------------ void enableForceSetTimer() { if (m_synchronised.load() == true) return; m_force_set_timer.store(true); }
void DialogSystem::receive(const MouseClickEvent &mce) { game::entities.each<Position, Solid, Dialog, Name>( [&](entityx::Entity e, Position &pos, Solid &dim, Dialog &d, Name &name) { static std::atomic_bool dialogRun; (void)e; (void)d; if (((mce.position.x > pos.x) & (mce.position.x < pos.x + dim.width)) && ((mce.position.y > pos.y) & (mce.position.y < pos.y + dim.height))) { if (!dialogRun.load()) { std::thread([&] { std::string questAssignedText; int newIndex; auto exml = game::engine.getSystem<WorldSystem>()->getXML()->FirstChildElement("Dialog"); dialogRun.store(true); if (e.has_component<Direction>()) d.talking = true; if (d.index == 9999) { ui::dialogBox(name.name, "", false, randomDialog[d.rindex % randomDialog.size()]); ui::waitForDialog(); } else if (exml != nullptr) { while (exml->StrAttribute("name") != name.name) exml = exml->NextSiblingElement(); exml = exml->FirstChildElement("text"); while (exml->IntAttribute("id") != d.index) exml = exml->NextSiblingElement(); auto oxml = exml->FirstChildElement("set"); if (oxml != nullptr) { do game::setValue(oxml->StrAttribute("id"), oxml->StrAttribute("value")); while ((oxml = oxml->NextSiblingElement())); game::briceUpdate(); } auto qxml = exml->FirstChildElement("quest"); if (qxml != nullptr) { const char *qname; auto qsys = game::engine.getSystem<QuestSystem>(); do { // assign quest qname = qxml->Attribute("assign"); if (qname != nullptr) { questAssignedText = qname; auto req = qxml->GetText(); qsys->assign(qname, qxml->StrAttribute("desc"), req ? req : ""); } // check / finish quest else { qname = qxml->Attribute("check"); if (qname != nullptr) { if (qname != nullptr && qsys->hasQuest(qname) && qsys->finish(qname) == 0) { d.index = 9999; } else { ui::dialogBox(name.name, "", false, "Finish my quest u nug"); ui::waitForDialog(); return; } // oldidx = d.index; // d.index = qxml->UnsignedAttribute("fail"); // goto COMMONAIFUNC; } } } while((qxml = qxml->NextSiblingElement())); } auto cxml = exml->FirstChildElement("content"); const char *content; if (cxml == nullptr) { content = randomDialog[d.rindex % randomDialog.size()].c_str(); } else { content = cxml->GetText() - 1; while (*++content && isspace(*content)); } ui::dialogBox(name.name, "", false, content); ui::waitForDialog(); if (!questAssignedText.empty()) ui::passiveImportantText(5000, ("Quest assigned:\n\"" + questAssignedText + "\"").c_str()); if (exml->QueryIntAttribute("nextid", &newIndex) == XML_NO_ERROR) d.index = newIndex; } d.talking = false; dialogRun.store(false); }).detach(); } } }); }
int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { s_gameFuncs = LoadGameFuncs(); assert(s_gameFuncs.valid); ImGuiIO& io = ImGui::GetIO(); //io.MemAllocFn = memory::malloc; //io.MemFreeFn = memory::free; //_crtBreakAlloc = 4015; s_queue = new util::ThreadSafeQueue<WindowEvent>(); g_LogInfo(SL_BUILD_DATE); // Log CPU features { #if 0 struct CPUInfo { union { int i[4]; }; } info = { 0 }; // Get number of functions __cpuid(info.i, 0); int nIds_ = info.i[0]; // Dump info std::vector<CPUInfo> data; for (int i = 0; i <= nIds_; ++i) { __cpuidex(info.i, i, 0); data.push_back(info); } // Vendor if(data.size() >= 0) { char vendor[13] = {0}; memcpy(vendor + 0, data[0].i + 1, 4); memcpy(vendor + 4, data[0].i + 3, 4); memcpy(vendor + 8, data[0].i + 2, 4); g_LogInfo("CPU Vendor: " + std::string(vendor)); } #endif // http://stackoverflow.com/questions/850774/how-to-determine-the-hardware-cpu-and-ram-on-a-machine int CPUInfo[4] = { 0 }; char CPUBrandString[0x40]; // Get the information associated with each extended ID. __cpuid(CPUInfo, 0x80000000); int nExIds = CPUInfo[0]; for (int i = 0x80000000; i <= nExIds; i++) { __cpuid(CPUInfo, i); // Interpret CPU brand string if (i == 0x80000002) memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo)); else if (i == 0x80000003) memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo)); else if (i == 0x80000004) memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo)); } //string includes manufacturer, model and clockspeed std::string brand(CPUBrandString); g_LogInfo(brand.substr(brand.find_first_not_of(" "))); SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); g_LogInfo("Logical processors: " + std::to_string(sysInfo.dwNumberOfProcessors)); MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); GlobalMemoryStatusEx(&statex); g_LogInfo("Total System Memory: " + std::to_string(statex.ullTotalPhys/1024/1024) + " MB"); } auto className = L"StarlightClassName"; WNDCLASSEXW wndClass = { 0 }; wndClass.cbSize = sizeof(WNDCLASSEXW); wndClass.style = CS_CLASSDC; wndClass.lpfnWndProc = WndProc; wndClass.hInstance = GetModuleHandleW(nullptr); wndClass.hCursor = LoadCursorW(nullptr, IDC_ARROW); wndClass.lpszClassName = className; RegisterClassExW(&wndClass); // Get desktop rectangle RECT desktopRect; GetClientRect(GetDesktopWindow(), &desktopRect); // Get window rectangle RECT windowRect = { 0, 0, 800, 600 }; // TODO: Config file? AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE); // Calculate window dimensions LONG windowWidth = windowRect.right - windowRect.left; LONG windowHeight = windowRect.bottom - windowRect.top; LONG x = desktopRect.right / 2 - windowWidth / 2; LONG y = desktopRect.bottom / 2 - windowHeight / 2; #ifdef _DEBUG // Move the screen to the right monitor on JOTARO wchar_t computerName[MAX_COMPUTERNAME_LENGTH + 1]; DWORD dwSize = sizeof(computerName); GetComputerNameW(computerName, &dwSize); if (wcscmp(computerName, L"JOTARO") == 0) { x += 1920; } #endif s_config.Load(); s_hwnd = CreateWindowExW( 0L, className, L"Starlight", WS_OVERLAPPEDWINDOW, x, y, windowWidth, windowHeight, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr ); // Show the window ShowWindow(s_hwnd, SW_MAXIMIZE); UpdateWindow(s_hwnd); // Create thread s_running.store(true); unsigned int threadID; HANDLE thread = (HANDLE) _beginthreadex(nullptr, 0, MyThreadFunction, nullptr, 0, &threadID); if (!thread) { // Error creating thread return 1; } // Watch Lua directory hDirectoryChange = FindFirstChangeNotification(L"../starlight/", TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE); if (!hDirectoryChange) { g_LogInfo("Error creating directory change notification handle: Lua reload on save will not work."); } // Message loop MSG msg; while (s_running.load() && GetMessageW(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessageW(&msg); } WaitForSingleObject(thread, INFINITE); CloseHandle(thread); if (hDirectoryChange) { if (!FindCloseChangeNotification(hDirectoryChange)) { g_LogInfo("Failed to close directory change notification handle."); } } s_gameFuncs.DestroyLogger(); io.Fonts->Clear(); s_config.Save(); delete s_queue; UnregisterClassW(className, GetModuleHandleW(nullptr)); _CrtDumpMemoryLeaks(); return 0; }
bool paused() { return sIsPaused.load(); }
bool isShutdownTime() const { return _shutdownFlag.load(); }
void producer( const map_ptr_t &map, const std::string &key, std::string value ) { while ( !g_is_done.load( std::memory_order_relaxed ) ) { auto access_token = map->get_exclusive_access( key ); map->set( key, value ); } }
bool is_connecting() { return connecting.load(); }
// ------------------------------------------------------------------------ bool isSynchronised() const { return m_synchronised.load(); }
void consumer( const map_ptr_t &map, const std::string &key ) { while ( !g_is_done.load( std::memory_order_relaxed ) ) { std::cout << "value for key [" << key << "] == " << map->get( key ) << std::endl; } }
bool is_connected() { return connected.load(); }