void ForumMessage::setRead(bool nr, bool affectsParents) { if(nr==_read) return; _read = nr; if(!affectsParents) return; if(!thread() || !thread()->group() || !thread()->group()->subscription()) return; if(thread()->group()->isSubscribed()) { if(_read) { thread()->incrementUnreadCount(-1); thread()->group()->incrementUnreadCount(-1); thread()->group()->subscription()->incrementUnreadCount(-1); } else { thread()->incrementUnreadCount(1); thread()->group()->incrementUnreadCount(1); thread()->group()->subscription()->incrementUnreadCount(1); } thread()->group()->setHasChanged(true); } _propertiesChanged = true; emit markedRead(this, nr); }
/** RPCS3 emulator has functions it desires to call from the GUI at times. Initialize them in here. */ void rpcs3_app::InitializeCallbacks() { EmuCallbacks callbacks; callbacks.exit = [this]() { quit(); }; callbacks.call_after = [=](std::function<void()> func) { RequestCallAfter(std::move(func)); }; callbacks.process_events = [this]() { RPCS3MainWin->update(); processEvents(); }; callbacks.get_kb_handler = [=]() -> std::shared_ptr<KeyboardHandlerBase> { switch (keyboard_handler type = g_cfg.io.keyboard) { case keyboard_handler::null: return std::make_shared<NullKeyboardHandler>(); case keyboard_handler::basic: { basic_keyboard_handler* ret = new basic_keyboard_handler(); ret->moveToThread(thread()); ret->SetTargetWindow(gameWindow); return std::shared_ptr<KeyboardHandlerBase>(ret); } default: fmt::throw_exception("Invalid keyboard handler: %s", type); } }; callbacks.get_mouse_handler = [=]() -> std::shared_ptr<MouseHandlerBase> { switch (mouse_handler type = g_cfg.io.mouse) { case mouse_handler::null: return std::make_shared<NullMouseHandler>(); case mouse_handler::basic: { basic_mouse_handler* ret = new basic_mouse_handler(); ret->moveToThread(thread()); ret->SetTargetWindow(gameWindow); return std::shared_ptr<MouseHandlerBase>(ret); } default: fmt::throw_exception("Invalid mouse handler: %s", type); } }; callbacks.get_pad_handler = [this]() -> std::shared_ptr<pad_thread> { return std::make_shared<pad_thread>(thread(), gameWindow); }; callbacks.get_gs_frame = [this]() -> std::unique_ptr<GSFrameBase> { extern const std::unordered_map<video_resolution, std::pair<int, int>, value_hash<video_resolution>> g_video_out_resolution_map; const auto size = g_video_out_resolution_map.at(g_cfg.video.resolution); int w = size.first; int h = size.second; if (guiSettings->GetValue(gui::gs_resize).toBool()) { w = guiSettings->GetValue(gui::gs_width).toInt(); h = guiSettings->GetValue(gui::gs_height).toInt(); } bool disableMouse = guiSettings->GetValue(gui::gs_disableMouse).toBool(); auto frame_geometry = gui::utils::create_centered_window_geometry(RPCS3MainWin->geometry(), w, h); gs_frame* frame; switch (video_renderer type = g_cfg.video.renderer) { case video_renderer::null: { frame = new gs_frame("Null", frame_geometry, RPCS3MainWin->GetAppIcon(), disableMouse); break; } case video_renderer::opengl: { frame = new gl_gs_frame(frame_geometry, RPCS3MainWin->GetAppIcon(), disableMouse); break; } case video_renderer::vulkan: { frame = new gs_frame("Vulkan", frame_geometry, RPCS3MainWin->GetAppIcon(), disableMouse); break; } #ifdef _MSC_VER case video_renderer::dx12: { frame = new gs_frame("DirectX 12", frame_geometry, RPCS3MainWin->GetAppIcon(), disableMouse); break; } #endif default: fmt::throw_exception("Invalid video renderer: %s" HERE, type); } gameWindow = frame; return std::unique_ptr<gs_frame>(frame); }; callbacks.get_gs_render = []() -> std::shared_ptr<GSRender> { switch (video_renderer type = g_cfg.video.renderer) { case video_renderer::null: return std::make_shared<NullGSRender>(); case video_renderer::opengl: return std::make_shared<GLGSRender>(); #if defined(_WIN32) || defined(HAVE_VULKAN) case video_renderer::vulkan: return std::make_shared<VKGSRender>(); #endif #ifdef _MSC_VER case video_renderer::dx12: return std::make_shared<D3D12GSRender>(); #endif default: fmt::throw_exception("Invalid video renderer: %s" HERE, type); } }; callbacks.get_audio = []() -> std::shared_ptr<AudioThread> { switch (audio_renderer type = g_cfg.audio.renderer) { case audio_renderer::null: return std::make_shared<NullAudioThread>(); #ifdef _WIN32 case audio_renderer::xaudio: return std::make_shared<XAudio2Thread>(); #endif #ifdef HAVE_ALSA case audio_renderer::alsa: return std::make_shared<ALSAThread>(); #endif #ifdef HAVE_PULSE case audio_renderer::pulse: return std::make_shared<PulseThread>(); #endif case audio_renderer::openal: return std::make_shared<OpenALThread>(); default: fmt::throw_exception("Invalid audio renderer: %s" HERE, type); } }; callbacks.get_msg_dialog = [=]() -> std::shared_ptr<MsgDialogBase> { return std::make_shared<msg_dialog_frame>(RPCS3MainWin->windowHandle()); }; callbacks.get_save_dialog = [=]() -> std::unique_ptr<SaveDialogBase> { return std::make_unique<save_data_dialog>(); }; callbacks.get_trophy_notification_dialog = [=]() -> std::unique_ptr<TrophyNotificationBase> { return std::make_unique<trophy_notification_helper>(gameWindow); }; callbacks.on_run = [=]() { OnEmulatorRun(); }; callbacks.on_pause = [=]() { OnEmulatorPause(); }; callbacks.on_resume = [=]() { OnEmulatorResume(); }; callbacks.on_stop = [=]() { OnEmulatorStop(); }; callbacks.on_ready = [=]() { OnEmulatorReady(); }; Emu.SetCallbacks(std::move(callbacks)); }
void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<ScriptCallStack>&&) { thread().workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, columnNumber, sourceURL); }
Parser::Parser(QUrl url) { this->url = url; qDebug() << "constructing parser on thread " << thread(); }
void AsinbowAPI::executeCommand(const std::string& command, const FB::JSObjectPtr& callback) { boost::thread thread(boost::bind(&AsinbowAPI::executeCommandWork, this, command, callback)); }
void WorkerGlobalScope::postTask(PassOwnPtr<Task> task) { thread()->runLoop().postTask(task); }
void ofxPDSPMidiOut::startMidiDaemon(){ runMidiDaemon = true; midiDaemonThread = thread( midiDaemonFunctionWrapper, this ); }
static int mainInternal(QApplication &a) { #ifdef MOBILE_DEVICE emugl = new MainUI(); emugl->resize(pixel_xres, pixel_yres); emugl->showFullScreen(); #endif EnableFZ(); // Disable screensaver #ifdef __SYMBIAN32__ QSystemScreenSaver ssObject(emugl); ssObject.setScreenSaverInhibit(); QScopedPointer<SymbianMediaKeys> mediakeys(new SymbianMediaKeys()); #elif defined(QT_HAS_SYSTEMINFO) QScreenSaver ssObject(emugl); ssObject.setScreenSaverEnabled(false); #endif #ifdef QT_HAS_SDL SDLJoystick joy(true); joy.startEventLoop(); SDL_Init(SDL_INIT_AUDIO); SDL_AudioSpec fmt, ret_fmt; memset(&fmt, 0, sizeof(fmt)); fmt.freq = 44100; fmt.format = AUDIO_S16; fmt.channels = 2; fmt.samples = 2048; fmt.callback = &mixaudio; fmt.userdata = (void *)0; if (SDL_OpenAudio(&fmt, &ret_fmt) < 0) { ELOG("Failed to open audio: %s", SDL_GetError()); } else { if (ret_fmt.samples != fmt.samples) // Notify, but still use it ELOG("Output audio samples: %d (requested: %d)", ret_fmt.samples, fmt.samples); if (ret_fmt.freq != fmt.freq || ret_fmt.format != fmt.format || ret_fmt.channels != fmt.channels) { ELOG("Sound buffer format does not match requested format."); ELOG("Output audio freq: %d (requested: %d)", ret_fmt.freq, fmt.freq); ELOG("Output audio format: %d (requested: %d)", ret_fmt.format, fmt.format); ELOG("Output audio channels: %d (requested: %d)", ret_fmt.channels, fmt.channels); ELOG("Provided output format does not match requirement, turning audio off"); SDL_CloseAudio(); } } // Audio must be unpaused _after_ NativeInit() SDL_PauseAudio(0); #else QScopedPointer<QThread> thread(new QThread); QScopedPointer<MainAudio> audio(new MainAudio()); audio->moveToThread(thread.data()); QObject::connect(thread.data(), SIGNAL(started()), audio.data(), SLOT(run())); thread->start(); #endif int ret = a.exec(); #ifndef QT_HAS_SDL thread->terminate(); #endif return ret; }
void SkylivePluginSkeleton::startPlugin() { std::cout << "SkylivePluginSkeleton initialized in thread " << thread() << std::endl; registerHandler((QString)"something", &SkylivePluginSkeleton::handle_getlogin); }
void TaskSchedulerTBB::thread_loop(size_t threadIndex) try { #if defined(__MIC__) setAffinity(threadIndex); #endif /* allocate thread structure */ Thread thread(threadIndex,this); threadLocal[threadIndex] = &thread; thread_local_thread = &thread; /* main thread loop */ while (!terminate) { auto predicate = [&] () { return anyTasksRunning || terminate; }; /* all threads are either spinning ... */ if (spinning) { while (!predicate()) __pause_cpu(32); } /* ... or waiting inside some condition variable */ else { //std::unique_lock<std::mutex> lock(mutex); Lock<MutexSys> lock(mutex); condition.wait(mutex, predicate); } if (terminate) break; /* special static load balancing for top level task sets */ #if TASKSCHEDULER_STATIC_LOAD_BALANCING if (executeTaskSet(thread)) continue; #endif /* work on available task */ steal_loop(thread, [&] () { return anyTasksRunning > 0; }, [&] () { atomic_add(&anyTasksRunning,+1); while (thread.tasks.execute_local(thread,nullptr)); atomic_add(&anyTasksRunning,-1); }); } /* decrement threadCount again */ atomic_add(&threadCounter,-1); /* wait for all threads to terminate */ while (threadCounter > 0) yield(); threadLocal[threadIndex] = nullptr; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; // FIXME: propagate to main thread threadLocal[threadIndex] = nullptr; exit(1); }
void main(int argc, char *argv[]) { char *p; setnetmtpt(net, sizeof(net), nil); ARGBEGIN{ case 'x': p = ARGF(); if(p == nil) usage(); setnetmtpt(net, sizeof(net), p); }ARGEND; fmtinstall('E', eipfmt); fmtinstall('I', eipfmt); fmtinstall('V', eipfmt); dhcpinit(); rfork(RFNOTEG|RFREND); thread(timerthread, 0); thread(stdinthread, 0); qlock(&dhcp.lk); dhcp.starttime = time(0); dhcp.fd = openlisten(net); dhcpsend(Discover); dhcp.state = Sselecting; dhcp.resend = 0; dhcp.timeout = 4; while(dhcp.state != Sbound) dhcprecv(); /* allows other clients on this machine */ close(dhcp.fd); dhcp.fd = -1; print("ip=%I\n", dhcp.client); print("mask=%I\n", dhcp.mask); print("end\n"); /* keep lease alive */ for(;;) { //fprint(2, "got lease for %d\n", dhcp.lease); qunlock(&dhcp.lk); sleep(dhcp.lease*500); /* wait half of lease time */ qlock(&dhcp.lk); //fprint(2, "try renue\n", dhcp.lease); dhcp.starttime = time(0); dhcp.fd = openlisten(net); dhcp.xid = time(0)*getpid(); dhcpsend(Request); dhcp.state = Srenewing; dhcp.resend = 0; dhcp.timeout = 1; while(dhcp.state != Sbound) dhcprecv(); /* allows other clients on this machine */ close(dhcp.fd); dhcp.fd = -1; } }
void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) { thread()->workerReportingProxy().reportException(errorMessage, lineNumber, columnNumber, sourceURL); }
void WorkerGlobalScope::postTask(PassOwnPtr<ExecutionContextTask> task) { thread()->runLoop().postTask(task); }
void ForumMessage::markToBeUpdated(bool toBe) { UpdateableItem::markToBeUpdated(toBe); if(toBe && thread()) { thread()->markToBeUpdated(); } }
bool WorkerGlobalScope::isContextThread() const { return thread()->isCurrentThread(); }
// @brief: starts webserver // @param[in]: port - port that the server listens on int WebHostEmulator::start(std::string port, LoginDatabase *database) { loginDatabase = database; int iResult; ListenSocket = INVALID_SOCKET; m_KeepAlive.lock(); KeepAlive = true; m_KeepAlive.unlock(); struct addrinfo *result = NULL; struct addrinfo hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and por iResult = getaddrinfo(NULL, port.c_str(), &hints, &result); if ( iResult != 0 ) { #ifdef __DEBUG printf("getaddrinfo failed with error: %d\n", iResult); #endif WSACleanup(); return 1; } // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { #ifdef __DEBUG printf("socket failed with error: %ld\n", WSAGetLastError()); #endif freeaddrinfo(result); WSACleanup(); return 1; } iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { #ifdef __DEBUG printf("bind failed with error: %d\n", WSAGetLastError()); #endif freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; } freeaddrinfo(result); iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { #ifdef __DEBUG printf("listen failed with error: %d\n", WSAGetLastError()); #endif closesocket(ListenSocket); WSACleanup(); return 1; } std::thread thread(&WebHostEmulator::HandleListen, this); thread.detach(); return 0; }
PictureLoader::~PictureLoader() { // This does not work with the destroyed() signal as this destructor is called after the main event loop is done. thread()->quit(); }
int main(int argc, char ** argv) { size_t n = argc == 2 ? DB::parse<UInt64>(argv[1]) : 100000; /* test(n, "Create and destroy boost::threadpool each iteration", [] { boost::threadpool::pool tp(1); tp.schedule(f); tp.wait(); });*/ test(n, "Create and destroy ThreadPool each iteration", [] { ThreadPool tp(1); tp.schedule(f); tp.wait(); }); test(n, "pthread_create, pthread_join each iteration", [] { pthread_t thread; if (pthread_create(&thread, nullptr, g, nullptr)) DB::throwFromErrno("Cannot create thread."); if (pthread_join(thread, nullptr)) DB::throwFromErrno("Cannot join thread."); }); test(n, "Create and destroy std::thread each iteration", [] { std::thread thread(f); thread.join(); }); /* { boost::threadpool::pool tp(1); test(n, "Schedule job for boost::threadpool each iteration", [&tp] { tp.schedule(f); tp.wait(); }); }*/ { ThreadPool tp(1); test(n, "Schedule job for Threadpool each iteration", [&tp] { tp.schedule(f); tp.wait(); }); } /* { boost::threadpool::pool tp(128); test(n, "Schedule job for boost::threadpool with 128 threads each iteration", [&tp] { tp.schedule(f); tp.wait(); }); }*/ { ThreadPool tp(128); test(n, "Schedule job for Threadpool with 128 threads each iteration", [&tp] { tp.schedule(f); tp.wait(); }); } return 0; }
/* **************************************************************** * Domain name resolver * **************************************************************** */ void main (int argc, const char *argv[]) { int opt; #if (0) /*******************************************************/ SERVTB *sp; int index; #endif /*******************************************************/ INADDR server_addr; T_BIND bind; /* * Pequena inicialização */ error_msg_to_log++; /* * Verifica se é SUPERUSUÁRIO */ if (geteuid () != 0) error ("$O usuário efetivo não é SUPERUSUÁRIO"); /* * Analisa as opções * * Sintaxe: * port_daemon [-v] <port_server_addr> ... */ while ((opt = getopt (argc, argv, "v")) != EOF) { switch (opt) { case 'v': /* Verbose */ vflag++; break; default: /* Erro */ putc ('\n', stderr); help (); } /* end switch */ } /* end while */ argv += optind; argc -= optind; #if (0) /*******************************************************/ if (argc == 0) help (); #endif /*******************************************************/ /* * Abre os "endpoint"s */ if ((udp_fd = t_open (udp_dev, O_RDWR, (T_INFO *)NULL)) < 0) error ("$*Não consegui abrir \"%s\"", udp_dev); /* * Obtém a porta local */ server_addr.a_port = PMAP_PORT; server_addr.a_addr = 0; bind.addr.len = sizeof (INADDR); bind.addr.maxlen = sizeof (INADDR); bind.addr.buf = &server_addr; if (t_bind (udp_fd, &bind, &bind) < 0) error ("$*Não consegui dar \"t_bind\" UDP"); send_req (); receive_answer (); #if (0) /*******************************************************/ /* * Cria um filho para enviar os pedidos de DNS. * O pai le os datagramas de resposta. */ if ((pidfilho = thread ()) < 0) error ("$*Não consegui criar um novo processo"); if (pidfilho > 0) pai (); else filho (); /* Não retorna */ #endif /*******************************************************/ } /* end port_mapper */
StatisticEmailSender::~StatisticEmailSender() { thread()->exit(); }
IoTObserver::IoTObserver(IoTObserverCb Cb) : m_callback(Cb), m_destroy(false), m_started(false) { m_observerThread[0] = thread(&IoTObserver::observerThread, this); }
static void updateLLDBEvent(LLDBPlugin* plugin, PDWriter* writer) { if (!plugin->process.IsValid()) { printf("process invalid\n"); return; } lldb::SBEvent evt; plugin->listener.WaitForEvent(1, evt); lldb::StateType state = lldb::SBProcess::GetStateFromEvent(evt); printf("event = %s\n", lldb::SBDebugger::StateAsCString(state)); if (lldb::SBProcess::GetRestartedFromEvent(evt)) { printf("lldb::SBProcess::GetRestartedFromEvent(evt)\n"); return; } switch (state) { case lldb::eStateInvalid: case lldb::eStateDetached: case lldb::eStateCrashed: case lldb::eStateUnloaded: return; case lldb::eStateExited: return; case lldb::eStateConnected: case lldb::eStateAttaching: case lldb::eStateLaunching: case lldb::eStateRunning: case lldb::eStateStepping: return; case lldb::eStateStopped: case lldb::eStateSuspended: { //call_test_step = true; bool fatal = false; bool selected_thread = false; for (uint32_t thread_index = 0; thread_index < plugin->process.GetNumThreads(); thread_index++) { lldb::SBThread thread(plugin->process.GetThreadAtIndex((size_t)thread_index)); lldb::SBFrame frame(thread.GetFrameAtIndex(0)); bool select_thread = false; lldb::StopReason stop_reason = thread.GetStopReason(); if (m_verbose) printf("tid = 0x%llx pc = 0x%llx ",thread.GetThreadID(),frame.GetPC()); switch (stop_reason) { case lldb::eStopReasonNone: if (m_verbose) printf("none\n"); break; case lldb::eStopReasonTrace: select_thread = true; plugin->state = PDDebugState_trace; if (m_verbose) printf("trace\n"); break; case lldb::eStopReasonPlanComplete: select_thread = true; sendExceptionState(plugin, writer); plugin->state = PDDebugState_trace; if (m_verbose) printf("plan complete\n"); break; case lldb::eStopReasonThreadExiting: if (m_verbose) printf("thread exiting\n"); break; case lldb::eStopReasonExec: if (m_verbose) printf("exec\n"); break; case lldb::eStopReasonInvalid: if (m_verbose) printf("invalid\n"); break; case lldb::eStopReasonException: { select_thread = true; printf("%d %d\n", plugin->state, PDDebugState_stopException); if (plugin->state != PDDebugState_stopException) sendExceptionState(plugin, writer); plugin->state = PDDebugState_stopException; if (m_verbose) printf("exception\n"); fatal = true; break; } case lldb::eStopReasonBreakpoint: { select_thread = true; if (plugin->state != PDDebugState_stopBreakpoint) sendExceptionState(plugin, writer); plugin->state = PDDebugState_stopBreakpoint; if (m_verbose) printf("breakpoint id = %lld.%lld\n",thread.GetStopReasonDataAtIndex(0),thread.GetStopReasonDataAtIndex(1)); break; } case lldb::eStopReasonWatchpoint: select_thread = true; if (m_verbose) printf("watchpoint id = %lld\n",thread.GetStopReasonDataAtIndex(0)); break; case lldb::eStopReasonSignal: select_thread = true; if (m_verbose) printf("signal %d\n",(int)thread.GetStopReasonDataAtIndex(0)); break; } if (select_thread && !selected_thread) { selected_thread = plugin->process.SetSelectedThread(thread); plugin->selectedThreadId = thread.GetThreadID(); } } } break; } }
int main(int argc, char* argv[]) { int i, j, task_num; struct timeval tv1, tv2, tv3; int dmiss_count = 0; pthread_t th[100]; if (argc != 5) { printf("Error: invalid option\n"); printf("usage: rt_task period runtime deadline task_num\n"); exit(EXIT_FAILURE); } #ifdef USE_SCHED_CPU prio = 0; /* priority. */ //printf("---- period :%d ms ----\n", atoi(argv[1])); period = ms_to_timespec(atoi(argv[1])); /* period. */ //printf("---- runtime :%d ms ----\n", atoi(argv[2])); runtime = ms_to_timespec(atoi(argv[2])); /* execution time. */ //printf("---- deadline:%d ms ----\n", atoi(argv[3])); deadline = ms_to_timespec( atoi(argv[3]) ); /* execution time. */ //printf("---- timeout:%d ms ----\n", 30000); timeout = ms_to_timespec(3000); /* timeout. */ #endif prio = getpid(); struct timespec ts1,ts2,ts3; task_num = atoi(argv[4]); int cpu; cpu_set_t set; cpu = sched_getcpu(); CPU_ZERO(&set); CPU_SET(cpu,&set); gettime(&ts1); #if 0 for(j=0; j<task_num; j++) pthread_create(&th[j], NULL, thread, (void *)NULL); pthread_setaffinity_np(pthread_self() ,sizeof(cpu_set_t), &set); for(j=0; j<task_num; j++) pthread_join(th[j],NULL); #else /* generate each job by using fork */ pid_t pid; for(j=0; j<task_num; j++){ pid= fork(); prio = DEFAULT_PRIO; if( -1 == pid) { fprintf(stderr,"can not fork\n"); break; }else if( 0 == pid){ fprintf(stderr,"fork! pid=%d\n",getpid()); thread(NULL); exit(EXIT_SUCCESS); } } pthread_setaffinity_np(pthread_self() ,sizeof(cpu_set_t), &set); int status = 0; while(1){ pid = wait(&status); if(pid == -1){ if(ECHILD == errno){ break; } else if (EINTR == errno) { fprintf(stderr,"synchronize\n"); continue; } err (EXIT_FAILURE, "wait error"); } fprintf (stderr,"parenet: child = %d, status=%d\n", pid, status); } #endif gettime(&ts2); fprintf(stderr,"total_time = %llu\n",timespec_to_ns_sub(&ts1,&ts2)); fprintf(stdout,"%llu\n",timespec_to_ns_sub(&ts1,&ts2)); return 0; }
void DedicatedWorkerGlobalScope::countDeprecation(UseCounter::Feature feature) const { thread()->workerObjectProxy().postTaskToMainExecutionContext(UseCounterTask::createDeprecation(feature)); }
void TServers::launchSingleThreadThriftServer(int port, boost::shared_ptr<TProcessor> &processor, thread &thrift_server) { // thread thrift_server = thread(buildNonBlockingServer, port, processor); thrift_server = thread(buildNonBlockingServer, port, processor); // thrift_server.join(); }
void DedicatedWorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& exceptionState) { Base::importScripts(urls, exceptionState); thread()->workerObjectProxy().reportPendingActivity(hasPendingActivity()); }
void WorkerGlobalScope::postTask(Task task) { thread().runLoop().postTask(WTF::move(task)); }
void WorkerGlobalScope::postTask(const WebTraceLocation& location, PassOwnPtr<ExecutionContextTask> task) { thread()->postTask(location, task); }
bool WorkerGlobalScope::isContextThread() const { return currentThread() == thread().threadID(); }
int main(int argc, char *argv[]) { std::string app_name(argv[0]); unsigned short port_number(via::comms::tcp_adaptor::DEFAULT_HTTP_PORT); // Get a port number from the user (the default is 80) if (argc > 2) { std::cerr << "Usage: " << app_name << " [port number]\n" << "E.g. " << app_name << " " << port_number << std::endl; return 1; } else if (argc == 2) { std::string port(argv[1]); port_number = atoi(port.c_str()); } std::cout << app_name << ": " << port_number << std::endl; try { // create an io_service for the server boost::asio::io_service io_service; // create an http_server and connect the request handler http_server_type http_server(io_service); http_server.request_received_event(request_handler); // connect the handler callback functions http_server.chunk_received_event(chunk_handler); http_server.request_expect_continue_event(expect_continue_handler); http_server.invalid_request_event(invalid_request_handler); http_server.socket_connected_event(connected_handler); http_server.socket_disconnected_event(disconnected_handler); http_server.message_sent_event(message_sent_handler); // start accepting http connections on the given port boost::system::error_code error(http_server.accept_connections(port_number)); if (error) { std::cerr << "Error: " << error.message() << std::endl; return 1; } // The signal set is used to register for termination notifications boost::asio::signal_set signals_(io_service); signals_.add(SIGINT); signals_.add(SIGTERM); #if defined(SIGQUIT) signals_.add(SIGQUIT); #endif // #if defined(SIGQUIT) // register the handle_stop callback signals_.async_wait([&http_server] (boost::system::error_code const& error, int signal_number) { handle_stop(error, signal_number, http_server); }); // Determine the number of concurrent threads supported size_t no_of_threads(std::thread::hardware_concurrency()); std::cout << "No of threads: " << no_of_threads << std::endl; if (no_of_threads > 0) { // Create a thread pool for the threads and run the asio io_service // in each of the threads. std::vector<std::shared_ptr<std::thread> > threads; for (std::size_t i = 0; i < no_of_threads; ++i) { std::shared_ptr<std::thread> thread(std::make_shared<std::thread> ([&io_service](){ io_service.run(); })); threads.push_back(thread); } // Wait for all threads in the pool to exit. for (std::size_t i(0); i < threads.size(); ++i) threads[i]->join(); } else io_service.run(); std::cout << "io_service.run, all work has finished" << std::endl; } catch (std::exception& e) { std::cerr << "Exception:" << e.what() << std::endl; } return 0; }