/*main(): sets limit to input from command line. * creates a forward & printing channnel, * creates innitial sieve thread, * sends values across channels chain, * sends KILL a negative value to trigure * thread_exit() and free resources * */ int main(int argc, char *argv[]) { thread_init(); int limit, i; int val = 0; char * channels[2]; //send and print channels. char * print[2]; //printing thread. Chan * fwd; //downstream neighbour. //take user input if(argc != 2) { fprintf(stderr, "usage test_seive <n>"); exit(1); } limit = atoi(argv[1]); /*channel 0 for printing channel 1 for pipe connection*/ if((channels[0] = (char *)create_chan()) == (char *)0 || (channels[1] = (char *)create_chan()) == (char *)0) { fprintf(stderr, "create_chan() failed. \n"); exit(1); } if((print[0] = (char *)create_chan()) == (char *)0) { fprintf(stderr, "create_chan() failed. \n"); exit(1); } fwd = (Chan *)channels[1]; print[1] = channels[0]; //create printing thread if(thread_spawn(print_thread, 2, print) == -1) { fprintf(stderr, "thread_spawn() failed \n"); exit(1); } //spawn first thread. if(thread_spawn(sieve, 2, channels) == -1){ fprintf(stderr, "thread_spawn() failed \n"); exit(1); } send(fwd, 2); //2 will always be the first prime for(i=3;i<=limit;i+=2) send(fwd, i); send(fwd, KILL); receive((Chan *)print[0], &val); //block till receive killswitch free((void *)fwd); free((void *)print[0]); return 0; }
void Startup(LPSTR lpCmdLine) { string4096 cmd; BOOL bModifyOptions = FALSE; strcpy_s(cmd,lpCmdLine); strlwr(cmd); if (strstr(cmd,"-?") || strstr(cmd,"-h")) { Help(); return; } if ((strstr(cmd,"-f")==0) && (strstr(cmd,"-g")==0) && (strstr(cmd,"-m")==0) && (strstr(cmd,"-s")==0) && (strstr(cmd,"-t")==0) && (strstr(cmd,"-c")==0) && (strstr(cmd,"-verify")==0) && (strstr(cmd,"-patch")==0)) { Help(); return; } if (strstr(cmd,"-o")) bModifyOptions = TRUE; // Give a LOG-thread a chance to startup InitCommonControls (); Sleep (150); thread_spawn (logThread, "log-update", 1024*1024,0); while (!logWindow) Sleep (150); u32 dwStartupTime = timeGetTime(); execute (cmd); // Show statistic char stats[256]; extern std::string make_time(u32 sec); extern HWND logWindow; u32 dwEndTime = timeGetTime(); sprintf (stats,"Time elapsed: %s",make_time((dwEndTime-dwStartupTime)/1000).c_str()); MessageBox (logWindow,stats,"Congratulation!",MB_OK|MB_ICONINFORMATION); bClose = TRUE; FlushLog (); Sleep (500); }
void Startup(LPSTR lpCmdLine) { char cmd[512],name[256]; BOOL bModifyOptions = FALSE; strcpy(cmd,lpCmdLine); strlwr(cmd); if (strstr(cmd,"-?") || strstr(cmd,"-h")) { Help(); return; } if (strstr(cmd,"-f")==0) { Help(); return; } if (strstr(cmd,"-o")) bModifyOptions = TRUE; // Give a LOG-thread a chance to startup InitCommonControls (); thread_spawn (logThread, "log-update", 1024*1024,0); Sleep (150); // Load project name[0]=0; sscanf (strstr(cmd,"-f")+2,"%s",name); //FS.update_path (name,"$game_levels$",name); FS.get_path ("$level$")->_set (name); CTimer dwStartupTime; dwStartupTime.Start(); xrCompiler (0); // Show statistic char stats[256]; extern std::string make_time(u32 sec); extern HWND logWindow; sprintf (stats,"Time elapsed: %s",make_time((dwStartupTime.GetElapsed_ms())/1000).c_str()); MessageBox (logWindow,stats,"Congratulation!",MB_OK|MB_ICONINFORMATION); bClose = TRUE; Sleep (500); }
void simple_condwait(void) { unsigned long long start; mutex_t mutex; cond_t cond; struct cond_mutex cm = { .mutex = &mutex, .cond = &cond, }; thread_t cond_signaler_tid; fprintf(stderr, "%s\n", __FUNCTION__); check("mutex_init", mutex_init(&mutex, PTHREAD_MUTEX_DEFAULT, 0), 0); check("cond_init", cond_init(&cond, 0), 0); check("mutex_lock", mutex_lock(&mutex), 0); check("thread_spawn", thread_spawn(&cond_signaler_tid, 2, cond_signaler, &cm), 0); thread_msleep(11); start = rt_timer_tsc(); check("cond_wait", cond_wait(&cond, &mutex, XN_INFINITE), 0); check_sleep("cond_wait", start); thread_msleep(10); check("mutex_unlock", mutex_unlock(&mutex), 0); check("thread_join", thread_join(cond_signaler_tid), 0); check("mutex_destroy", mutex_destroy(&mutex), 0); check("cond_destroy", cond_destroy(&cond), 0); }
void catching() { thread_h tid = thread_spawn("bsh echo Testing if bsh catches SIGINT..."); if (tid == INVALID_THREAD) { fprintf(stderr, "Failed to spawn thread\n"); abort(); } delay(); if (kill((int)tid, SIGINT) != 0) { fprintf(stderr, "Failed to send SIGINT\n"); abort(); } delay(); if (!is_thread_running(tid)) { fprintf(stderr, "Thread did not catch signal\n"); abort(); } delay(); kill_thread(tid, SIGKILL); }
THREAD_PROC ThreadedSocketAcceptor::socketAcceptorThread( void* p ) { AcceptorThreadInfo * info = reinterpret_cast < AcceptorThreadInfo* > ( p ); ThreadedSocketAcceptor* pAcceptor = info->m_pAcceptor; int s = info->m_socket; int port = info->m_port; delete info; int noDelay = 0; int sendBufSize = 0; int rcvBufSize = 0; socket_getsockopt( s, TCP_NODELAY, noDelay ); socket_getsockopt( s, SO_SNDBUF, sendBufSize ); socket_getsockopt( s, SO_RCVBUF, rcvBufSize ); int socket = 0; while ( ( !pAcceptor->isStopped() && ( socket = socket_accept( s ) ) >= 0 ) ) { if( noDelay ) socket_setsockopt( socket, TCP_NODELAY ); if( sendBufSize ) socket_setsockopt( socket, SO_SNDBUF, sendBufSize ); if( rcvBufSize ) socket_setsockopt( socket, SO_RCVBUF, rcvBufSize ); Sessions sessions = pAcceptor->m_portToSessions[port]; ThreadedSocketConnection * pConnection = new ThreadedSocketConnection ( socket, sessions, pAcceptor->getLog() ); ConnectionThreadInfo* info = new ConnectionThreadInfo( pAcceptor, pConnection ); { Locker l( pAcceptor->m_mutex ); std::stringstream stream; stream << "Accepted connection from " << socket_peername( socket ) << " on port " << port; if( pAcceptor->getLog() ) pAcceptor->getLog()->onEvent( stream.str() ); thread_id thread; if ( !thread_spawn( &socketConnectionThread, info, thread ) ) { delete info; delete pConnection; } else pAcceptor->addThread( socket, thread ); } } if( !pAcceptor->isStopped() ) pAcceptor->removeThread( s ); return 0; }
void HttpServer::start() throw ( ConfigError, RuntimeError ) { m_stop = false; onConfigure( m_settings ); onInitialize( m_settings ); if( !thread_spawn( &startThread, this, m_threadid ) ) throw RuntimeError("Unable to spawn thread"); }
void ndp_initialize(const char *_ifname, const uint8_t _src_ip_addr[]) { if(is_initialized) return; is_initialized = 1; strcpy(ifname, _ifname); memcpy(src_ip_addr, _src_ip_addr, IP_ADDR_LEN); for(int i = 0; i < NDP_TABLE_MAX_SIZE; ++i) { ndp_table[i] = 0; } receiver_thread = thread_spawn(&recv_loop, 0); sender_thread = thread_spawn(send_loop, 0); atexit(ndp_stop); }
void* sockio_test() { thread_t *server, *client; banner("sockio"); server = thread_spawn("sockio_test_server", sockio_test_server, NULL); client = thread_spawn("sockio_test_client", sockio_test_client, NULL); thread_yield(); thread_join(server, NULL); thread_join(client, NULL); //kill(getpid(), SIGUSR1); output("done.\n"); return NULL; }
void ThreadedSocketAcceptor::onStart() { Sockets::iterator i; for( i = m_sockets.begin(); i != m_sockets.end(); ++i ) { Locker l( m_mutex ); int port = m_socketToPort[*i]; AcceptorThreadInfo* info = new AcceptorThreadInfo( this, *i, port ); thread_id thread; thread_spawn( &socketAcceptorThread, info, thread ); addThread( *i, thread ); } }
/*sieve: takes 2 channel pointers; a printing thread, * and its upstream neigbour. * when innitialised value becomes threads this threads, * 'first' and the value is passed to the printing channel. * where the printing thread will eventually be scheduled, * and receive the value. * if the KILL switch is received (-1), and their is no * downstream neibour the value is passed to the print thread. * otherwise the KILL switch is passed on. * */ void sieve(int argc, char *channels[]) { int first, recv; /*may have to use memcpy here*/ Chan * input = (Chan *)channels[1]; Chan * print = (Chan *)channels[0]; Chan * fwd = (Chan *)0; //downstream neighbour. receive(input, &first); send(print, first); while(1) { //wait for message. receive(input, &recv); /* if first and -1 thensimply destroy*/ if(recv == -1 && fwd == (Chan *)0) { send(print, recv); free((void *)input); send(print, recv); thread_exit(); } else if (recv == -1) {/*else we need to pass -1 on before destroy*/ send(fwd, recv); free((void *)input); thread_exit(); } if (recv % first == 0) continue; else // candidate prime { //if no downstream neighbour create a new one make fwd point to shared channel. if(fwd == (Chan *)0) { /*test if channel has aready been created*/ if((fwd = create_chan()) == (Chan *)0) { fprintf(stderr, "create_chan() Failed\n"); exit(1); } channels[1] = (char *)fwd; //pass on value if(thread_spawn(sieve, 2, channels) == -1) { fprintf(stderr, "thread_spawn() failed\n"); exit(1); } } } send(fwd, recv);//no need to yield because receive will block until ready. } }
void Acceptor::start() throw ( ConfigError, RuntimeError ) { QF_STACK_PUSH( Acceptor::start ) m_stop = false; onConfigure( m_settings ); onInitialize( m_settings ); HttpServer::startGlobal( m_settings ); if( !thread_spawn( &startThread, this, m_threadid ) ) throw RuntimeError("Unable to spawn thread"); QF_STACK_POP }
int main(int argc, const char *argv[]) { int packets_in_buf = 1024; const char *payload = (const char[32]){0}; int payload_sz = 32; if (argc == 1) { FATAL("Usage: %s [target ip:port] [target ...]", argv[0]); } struct net_addr *target_addrs = calloc(argc-1, sizeof(struct net_addr)); int thread_num = argc - 1; int t; for (t = 0; t < thread_num; t++) { const char *target_addr_str = argv[t+1]; parse_addr(&target_addrs[t], target_addr_str); fprintf(stderr, "[*] Sending to %s, send buffer %i packets\n", addr_to_str(&target_addrs[t]), packets_in_buf); } struct state *array_of_states = calloc(thread_num, sizeof(struct state)); for (t = 0; t < thread_num; t++) { struct state *state = &array_of_states[t]; state->target_addr = &target_addrs[t]; state->packets_in_buf = packets_in_buf; state->payload = payload; state->payload_sz = payload_sz; state->src_port = 11404; thread_spawn(thread_loop, state); } while (1) { struct timeval timeout = NSEC_TIMEVAL(MSEC_NSEC(1000UL)); while (1) { int r = select(0, NULL, NULL, NULL, &timeout); if (r != 0) { continue; } if (TIMEVAL_NSEC(&timeout) == 0) { break; } } // pass } return 0; }
void simple_launch_and_kill() { thread_h tid = thread_spawn("bsh echo Testing if we can kill this bsh thread..."); if (tid == INVALID_THREAD) { fprintf(stderr, "Failed to spawn thread\n"); abort(); } delay(); kill_thread(tid, SIGKILL); }
void ThreadedSocketInitiator::doConnect( const SessionID& s, const Dictionary& d ) { try { Session* session = Session::lookupSession( s ); if( !session->isSessionTime(UtcTimeStamp()) ) return; Log* log = session->getLog(); std::string address; short port = 0; std::string sourceAddress; short sourcePort = 0; getHost( s, d, address, port, sourceAddress, sourcePort ); socket_handle socket = socket_createConnector(); if( m_noDelay ) socket_setsockopt( socket, TCP_NODELAY ); if( m_sendBufSize ) socket_setsockopt( socket, SO_SNDBUF, m_sendBufSize ); if( m_rcvBufSize ) socket_setsockopt( socket, SO_RCVBUF, m_rcvBufSize ); setPending( s ); log->onEvent( "Connecting to " + address + " on port " + IntConvertor::convert((unsigned short)port) + " (Source " + sourceAddress + ":" + IntConvertor::convert((unsigned short)sourcePort) + ")"); ThreadedSocketConnection* pConnection = new ThreadedSocketConnection( s, socket, address, port, getLog(), sourceAddress, sourcePort ); ThreadPair* pair = new ThreadPair( this, pConnection ); { Locker l( m_mutex ); thread_id thread; if ( thread_spawn( &socketThread, pair, thread ) ) { addThread( socket, thread ); } else { delete pair; pConnection->disconnect(); delete pConnection; setDisconnected( s ); } } } catch ( std::exception& ) {} }
void cond_destroy_whilewait(void) { unsigned long long start; mutex_t mutex; cond_t cond; struct cond_mutex cm = { .mutex = &mutex, .cond = &cond, .tid = thread_self(), }; thread_t cond_destroyer_tid; struct sigaction sa = { .sa_handler = sighandler, .sa_flags = SA_RESTART, }; sigemptyset(&sa.sa_mask); fprintf(stderr, "%s\n", __FUNCTION__); check_unix("sigaction", sigaction(SIGRTMIN, &sa, NULL), 0); check("mutex_init", mutex_init(&mutex, PTHREAD_MUTEX_DEFAULT, 0), 0); check("cond_init", cond_init(&cond, 0), 0); check("mutex_lock", mutex_lock(&mutex), 0); check("thread_spawn", thread_spawn(&cond_destroyer_tid, 2, cond_destroyer, &cm), 0); thread_msleep(11); start = rt_timer_tsc(); #ifdef XENO_POSIX check("cond_wait", cond_wait(&cond, &mutex, 10 * NS_PER_MS), -ETIMEDOUT); check_sleep("cond_wait", start); thread_msleep(10); check("mutex_unlock", mutex_unlock(&mutex), 0); #else /* native */ check("cond_wait", cond_wait(&cond, &mutex, XN_INFINITE), -EIDRM); check_sleep("cond_wait", start); #endif /* native */ check("thread_join", thread_join(cond_destroyer_tid), 0); check("mutex_destroy", mutex_destroy(&mutex), 0); #ifdef XENO_POSIX check("cond_destroy", cond_destroy(&cond), 0); #else /* native */ check("cond_destroy", cond_destroy(&cond), -ESRCH); #endif /* native */ }
void memory_model_sct::program_order( symex_target_equationt &equation) { per_thread_mapt per_thread_map; build_per_thread_map(equation, per_thread_map); thread_spawn(equation, per_thread_map); // iterate over threads for(per_thread_mapt::const_iterator t_it=per_thread_map.begin(); t_it!=per_thread_map.end(); t_it++) { const event_listt &events=t_it->second; // iterate over relevant events in the thread event_it previous=equation.SSA_steps.end(); for(event_listt::const_iterator e_it=events.begin(); e_it!=events.end(); e_it++) { if(is_memory_barrier(*e_it)) continue; if(previous==equation.SSA_steps.end()) { // first one? previous=*e_it; continue; } add_constraint( equation, before(previous, *e_it), "po", (*e_it)->source); previous=*e_it; } } }
int pthread_create( pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { pthread_initialize(); if (thread == NULL || start_routine == NULL) return_errno(EINVAL, EINVAL); // if (thread_ctrl(THREAD_CTRL_GETTHREADS) >= PTHREAD_THREADS_MAX) // return_errno(EAGAIN, EAGAIN); if (attr == NULL) *thread = (pthread_t)thread_spawn(NULL, start_routine, arg); else *thread = (pthread_t)thread_spawn_with_attr(NULL, start_routine, arg, (thread_attr_t)(*attr)); if (*thread == NULL) { errno = ENOMEM; return -1; } return OK; }
void CRenderDevice::Run () { // DUMP_PHASE; g_bLoaded = FALSE; Log ("Starting engine..."); thread_name ("X-RAY Primary thread"); // Startup timers and calculate timer delta dwTimeGlobal = 0; Timer_MM_Delta = 0; { u32 time_mm = timeGetTime (); while (timeGetTime()==time_mm); // wait for next tick u32 time_system = timeGetTime (); u32 time_local = TimerAsync (); Timer_MM_Delta = time_system-time_local; } // Start all threads // InitializeCriticalSection (&mt_csEnter); // InitializeCriticalSection (&mt_csLeave); mt_csEnter.Enter (); mt_bMustExit = FALSE; thread_spawn (mt_Thread,"X-RAY Secondary thread",0,0); // Message cycle seqAppStart.Process (rp_AppStart); //CHK_DX(HW.pDevice->Clear(0,0,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1,0)); m_pRender->ClearTarget (); message_loop (); seqAppEnd.Process (rp_AppEnd); // Stop Balance-Thread mt_bMustExit = TRUE; mt_csEnter.Leave (); while (mt_bMustExit) Sleep(0); // DeleteCriticalSection (&mt_csEnter); // DeleteCriticalSection (&mt_csLeave); }
void CGameSpy_Browser::RefreshList_Full(bool Local, const char* FilterStr) { if (!m_pGSBrowser) return; SBState state = xrGS_ServerBrowserState(m_pGSBrowser); if((state != sb_connected) && (state != sb_disconnected)) { xrGS_ServerBrowserHalt(m_pGSBrowser); Msg("xrGSB Refresh Stopped\n"); }; xrGS_ServerBrowserClear(m_pGSBrowser); // do an update SBError error = sbe_noerror; if(!Local) { m_refresh_lock.Enter(); m_refresh_lock.Leave(); if (m_bAbleToConnectToMasterServer) { RefreshData* pRData = xr_new<RefreshData>(); strcpy(pRData->FilterStr, FilterStr); pRData->pGSBrowser = this; m_bTryingToConnectToMasterServer = true; if (MainMenu()) MainMenu()->Show_CTMS_Dialog(); thread_spawn(RefreshInternetList, "GS Internet Refresh", 0, pRData); } if (error != sbe_noerror || !m_bAbleToConnectToMasterServer) { MainMenu()->SetErrorDialog(CMainMenu::ErrMasterServerConnectFailed); } } else error = xrGS_ServerBrowserLANUpdate(m_pGSBrowser, m_pServerList ? SBTrue : SBFalse); if (error != sbe_noerror) { Msg("! xrGSB Error - %s", xrGS_ServerBrowserErrorDesc(m_pGSBrowser, error)); } };
unsigned int proc_create(void *elf_addr, unsigned int quota) { unsigned int pid, id; id = get_curid(); pid = thread_spawn((void *) proc_start_user, id, quota); elf_load(elf_addr, pid); uctx_pool[pid].es = CPU_GDT_UDATA | 3; uctx_pool[pid].ds = CPU_GDT_UDATA | 3; uctx_pool[pid].cs = CPU_GDT_UCODE | 3; uctx_pool[pid].ss = CPU_GDT_UDATA | 3; uctx_pool[pid].esp = VM_USERHI; uctx_pool[pid].eflags = FL_IF; uctx_pool[pid].eip = elf_entry(elf_addr); seg_init_proc(get_pcpu_idx(), pid); return pid; }
void task_manager::startup() { start_time.Start(); tasks_completed = 0; //create_user( ); thread_spawn (task_manager::user_thread_proc,"release-user",1024*1024,this); for(;;) { Sleep(1); bool user_inited = false; init_lock.Enter(); user_inited = !!_user; init_lock.Leave(); if( user_inited ) break; } R_ASSERT( _user ); FPU::m64r (); Memory.mem_compact (); }
void Startup(LPSTR lpCmdLine) { char cmd[512],name[256]; BOOL bModifyOptions = FALSE; strcpy(cmd,lpCmdLine); strlwr(cmd); if (strstr(cmd,"-?") || strstr(cmd,"-h")) { Help(); return; } if (strstr(cmd,"-f")==0) { Help(); return; } if (strstr(cmd,"-o")) bModifyOptions = TRUE; if (strstr(cmd,"-gi")) b_radiosity = TRUE; if (strstr(cmd,"-noise")) b_noise = TRUE; if (strstr(cmd,"-nosun")) b_nosun = TRUE; // Give a LOG-thread a chance to startup //_set_sbh_threshold(1920); InitCommonControls (); thread_spawn (logThread, "log-update", 1024*1024,0); Sleep (150); // Faster FPU SetPriorityClass (GetCurrentProcess(),NORMAL_PRIORITY_CLASS); /* u32 dwMin = 1800*(1024*1024); u32 dwMax = 1900*(1024*1024); if (0==SetProcessWorkingSetSize(GetCurrentProcess(),dwMin,dwMax)) { clMsg("*** Failed to expand working set"); }; */ // Load project name[0]=0; sscanf(strstr(cmd,"-f")+2,"%s",name); string256 prjName; FS.update_path (prjName,"$game_levels$",strconcat(prjName,name,"\\build.prj")); string256 phaseName; Phase (strconcat(phaseName,"Reading project [",name,"]...")); string256 inf; extern HWND logWindow; IReader* F = FS.r_open(prjName); if (NULL==F){ sprintf (inf,"Build failed!\nCan't find level: '%s'",name); clMsg (inf); MessageBox (logWindow,inf,"Error!",MB_OK|MB_ICONERROR); return; } // Version u32 version; F->r_chunk (EB_Version,&version); clMsg ("version: %d",version); R_ASSERT(XRCL_CURRENT_VERSION==version); // Header b_params Params; F->r_chunk (EB_Parameters,&Params); // Show options if needed if (bModifyOptions) { Phase ("Project options..."); HMODULE L = LoadLibrary ("xrLC_Options.dll"); void* P = GetProcAddress (L,"_frmScenePropertiesRun"); R_ASSERT (P); xrOptions* O = (xrOptions*)P; int R = O(&Params,version,false); FreeLibrary (L); if (R==2) { ExitProcess(0); } } // Conversion Phase ("Converting data structures..."); pBuild = xr_new<CBuild>(); pBuild->Load (Params,*F); xr_delete (F); // Call for builder string256 lfn; CTimer dwStartupTime; dwStartupTime.Start(); FS.update_path (lfn,_game_levels_,name); pBuild->Run (lfn); xr_delete (pBuild); // Show statistic extern std::string make_time(u32 sec); u32 dwEndTime = dwStartupTime.GetElapsed_ms(); sprintf (inf,"Time elapsed: %s",make_time(dwEndTime/1000).c_str()); clMsg ("Build succesful!\n%s",inf); MessageBox (logWindow,inf,"Congratulation!",MB_OK|MB_ICONINFORMATION); // Close log bClose = TRUE; Sleep (500); }
void sig_norestart_double(void) { unsigned long long start; mutex_t mutex; cond_t cond; struct cond_mutex cm = { .mutex = &mutex, .cond = &cond, .tid = thread_self(), }; thread_t double_killer_tid; struct sigaction sa = { .sa_handler = sighandler, .sa_flags = 0, }; sigemptyset(&sa.sa_mask); fprintf(stderr, "%s\n", __FUNCTION__); check_unix("sigaction", sigaction(SIGRTMIN, &sa, NULL), 0); check("mutex_init", mutex_init(&mutex, PTHREAD_MUTEX_DEFAULT, 0), 0); check("cond_init", cond_init(&cond, 0), 0); check("mutex_lock", mutex_lock(&mutex), 0); check("thread_spawn", thread_spawn(&double_killer_tid, 2, double_killer, &cm), 0); thread_msleep(11); sig_seen = 0; start = rt_timer_tsc(); check("cond_wait", cond_wait(&cond, &mutex, XN_INFINITE), 0); check_sleep("cond_wait", start); check("sig_seen", sig_seen, 2); thread_msleep(10); check("mutex_unlock", mutex_unlock(&mutex), 0); check("thread_join", thread_join(double_killer_tid), 0); check("mutex_destroy", mutex_destroy(&mutex), 0); check("cond_destroy", cond_destroy(&cond), 0); } void sig_restart_double(void) { unsigned long long start; mutex_t mutex; cond_t cond; struct cond_mutex cm = { .mutex = &mutex, .cond = &cond, .tid = thread_self(), }; thread_t double_killer_tid; struct sigaction sa = { .sa_handler = sighandler, .sa_flags = SA_RESTART, }; sigemptyset(&sa.sa_mask); fprintf(stderr, "%s\n", __FUNCTION__); check_unix("sigaction", sigaction(SIGRTMIN, &sa, NULL), 0); check("mutex_init", mutex_init(&mutex, PTHREAD_MUTEX_DEFAULT, 0), 0); check("cond_init", cond_init(&cond, 0), 0); check("mutex_lock", mutex_lock(&mutex), 0); check("thread_spawn", thread_spawn(&double_killer_tid, 2, double_killer, &cm), 0); thread_msleep(11); sig_seen = 0; start = rt_timer_tsc(); check("cond_wait", cond_wait(&cond, &mutex, XN_INFINITE), 0); check_sleep("cond_wait", start); check("sig_seen", sig_seen, 2); thread_msleep(10); check("mutex_unlock", mutex_unlock(&mutex), 0); check("thread_join", thread_join(double_killer_tid), 0); check("mutex_destroy", mutex_destroy(&mutex), 0); check("cond_destroy", cond_destroy(&cond), 0); }
void sig_norestart_condwait(void) { unsigned long long start; mutex_t mutex; cond_t cond; struct cond_mutex cm = { .mutex = &mutex, .cond = &cond, .tid = thread_self(), }; thread_t cond_killer_tid; struct sigaction sa = { .sa_handler = sighandler, .sa_flags = 0, }; sigemptyset(&sa.sa_mask); fprintf(stderr, "%s\n", __FUNCTION__); check_unix("sigaction", sigaction(SIGRTMIN, &sa, NULL), 0); check("mutex_init", mutex_init(&mutex, PTHREAD_MUTEX_DEFAULT, 0), 0); check("cond_init", cond_init(&cond, 0), 0); check("mutex_lock", mutex_lock(&mutex), 0); check("thread_spawn", thread_spawn(&cond_killer_tid, 2, cond_killer, &cm), 0); thread_msleep(11); start = rt_timer_tsc(); sig_seen = 0; #ifdef XENO_POSIX check("cond_wait", cond_wait(&cond, &mutex, XN_INFINITE), 0); #else /* native */ { int err = cond_wait(&cond, &mutex, XN_INFINITE); if (err == 0) err = -EINTR; check("cond_wait", err, -EINTR); } #endif /* native */ check_sleep("cond_wait", start); check("sig_seen", sig_seen, 1); check("mutex_unlock", mutex_unlock(&mutex), 0); check("thread_join", thread_join(cond_killer_tid), 0); check("mutex_destroy", mutex_destroy(&mutex), 0); check("cond_destroy", cond_destroy(&cond), 0); } void sig_restart_condwait(void) { unsigned long long start; mutex_t mutex; cond_t cond; struct cond_mutex cm = { .mutex = &mutex, .cond = &cond, .tid = thread_self(), }; thread_t cond_killer_tid; struct sigaction sa = { .sa_handler = sighandler, .sa_flags = 0, }; sigemptyset(&sa.sa_mask); fprintf(stderr, "%s\n", __FUNCTION__); check_unix("sigaction", sigaction(SIGRTMIN, &sa, NULL), 0); check("mutex_init", mutex_init(&mutex, PTHREAD_MUTEX_DEFAULT, 0), 0); check("cond_init", cond_init(&cond, 0), 0); check("mutex_lock", mutex_lock(&mutex), 0); check("thread_spawn", thread_spawn(&cond_killer_tid, 2, cond_killer, &cm), 0); thread_msleep(11); start = rt_timer_tsc(); sig_seen = 0; #ifdef XENO_POSIX check("cond_wait", cond_wait(&cond, &mutex, XN_INFINITE), 0); #else /* native */ { int err = cond_wait(&cond, &mutex, XN_INFINITE); if (err == 0) err = -EINTR; check("cond_wait", err, -EINTR); } #endif /* native */ check_sleep("cond_wait", start); check("sig_seen", sig_seen, 1); check("mutex_unlock", mutex_unlock(&mutex), 0); check("thread_join", thread_join(cond_killer_tid), 0); check("mutex_destroy", mutex_destroy(&mutex), 0); check("cond_destroy", cond_destroy(&cond), 0); } void *mutex_killer(void *cookie) { unsigned long long start; struct cond_mutex *cm = cookie; start = rt_timer_tsc(); check("mutex_lock", mutex_lock(cm->mutex), 0); check_sleep("mutex_lock", start); check("cond_signal", cond_signal(cm->cond), 0); thread_msleep(10); check("thread_kill", thread_kill(cm->tid, SIGRTMIN), 0); check("mutex_unlock", mutex_unlock(cm->mutex), 0); return NULL; }
int main(int argc, char **argv) { quantum_reg qr; int i; int width, swidth; int x = 0; int N; int c, q, a, b, factor; #if defined(SPEC_CPU) spec_srand(26); #else srandom(time(0)); #endif /* SPEC_CPU */ if(argc == 1) { printf("Usage: shor [number]\n\n"); return 3; } N = atoi(argv[1]); if(N<15) { printf("Invalid number\n\n"); return 3; } width = quantum_getwidth(N * N); swidth = quantum_getwidth(N); printf("N = %i, %i qubits required\n", N, width + 3* swidth + 2); if(argc >= 3) { x = atoi(argv[2]); } while((quantum_gcd(N, x) > 1) || (x < 2)) { #if defined(SPEC_CPU) x = (long)(spec_rand() * 2147483647L) % N; #else x = random() % N; #endif /* SPEC_CPU */ } printf("Random seed: %i\n", x); qr = quantum_new_qureg(0, width); for (i = 0; i < width; i++) quantum_hadamard(i, &qr); quantum_addscratch(3* swidth + 2, &qr); cur_reg = &qr; pthread_t push_thread_id = thread_spawn((void*)&push_thread_func); #if defined(SIMICS) MAGIC(9006); #endif #if defined(SIMICS) MAGIC(9007); #endif //~ syscall(500, 0); // enter detailed simulation #ifdef MIPS_1 asm volatile ("addiu $0,$0,3720"); #endif quantum_exp_mod_n(N, x, width, swidth, &qr); for(i=0;i<3*swidth+2;i++) { quantum_bmeasure(0, &qr); } quantum_qft(width, &qr); for(i=0; i<width/2; i++) { quantum_cnot(i, width - i - 1, &qr); quantum_cnot(width - i - 1, i, &qr); quantum_cnot(i, width - i - 1, &qr); } c = quantum_measure(qr); if(c==-1) { printf("Impossible Measurement!\n"); exit(1); } if(c==0) { printf("Measured zero, try again.\n"); exit(2); } q = 1 << (width); printf("Measured %i (%f), ", c, (float) c / q); quantum_frac_approx(&c, &q, width); printf("fractional approximation is %i/%i.\n", c, q); if((q % 2 == 1) && (2*q<(1<<width))) { printf("Odd denominator, trying to expand by 2.\n"); q *= 2; } if(q % 2 == 1) { printf("Odd period, try again.\n"); exit(2); } printf("Possible period is %i.\n", q); a = quantum_ipow(x, q / 2) + 1 % N; b = quantum_ipow(x, q / 2) - 1 % N; a = quantum_gcd(N, a); b = quantum_gcd(N, b); if (a > b) factor = a; else factor = b; //thread_destroy(push_thread_id); cur_reg = NULL; #if defined(SIMICS) MAGIC(9008); #endif if((factor < N) && (factor > 1)) { printf("%i = %i * %i\n", N, factor, N / factor); } else { printf("Unable to determine factors, try again.\n"); #if defined(SPEC_CPU) exit(0); #else exit(2); #endif /* SPEC_CPU */ } quantum_delete_qureg(&qr); /* printf("Memory leak: %i bytes\n", (int) quantum_memman(0)); */ return 0; }
int main(int argc, char *argv[]) { int i; int j; thread_id_t *client_id; thread_id_t *server_id; signal(SIGINT, signal_handler); parse_args(argc, argv); if (mach_timebase_info(&g_timebase) != KERN_SUCCESS) { fprintf(stderr, "Can't get mach_timebase_info!\n"); exit(1); } calibrate_client_work(); /* * If we're using affinity create an empty namespace now * so this is shared by all our offspring. */ if (affinity) thread_setup(0); server_id = (thread_id_t *) malloc(num_servers * sizeof(thread_id_t)); server_port_name = (char **) malloc(num_servers * sizeof(char *)); server_port_args = (struct port_args *)calloc(sizeof(struct port_args), num_servers); if (!server_id || !server_port_name || !server_port_args) { fprintf(stderr, "malloc/calloc of %d server book keeping structs failed\n", num_servers); exit(1); } if (verbose) printf("creating %d servers\n", num_servers); for (i = 0; i < num_servers; i++) { server_port_name[i] = (char *) malloc(sizeof("PORT.pppppp.xx")); /* PORT names include pid of main process for disambiguation */ sprintf(server_port_name[i], "PORT.%06d.%02d", getpid(), i); thread_spawn(&server_id[i], server, (void *) (long) i); } int totalclients = num_servers * num_clients; int totalmsg = num_msgs * totalclients; struct timeval starttv, endtv, deltatv; /* * Wait for all servers to have registered all ports before starting * the clients and the clock. */ wait_for_servers(); printf("%d server%s, %d client%s per server (%d total) %u messages...", num_servers, (num_servers > 1)? "s" : "", num_clients, (num_clients > 1)? "s" : "", totalclients, totalmsg); fflush(stdout); /* Call gettimeofday() once and throw away result; some implementations * (like Mach's) cache some time zone info on first call. */ gettimeofday(&starttv, NULL); gettimeofday(&starttv, NULL); client_id = (thread_id_t *) malloc(totalclients * sizeof(thread_id_t)); if (verbose) printf("creating %d clients\n", totalclients); for (i = 0; i < num_servers; i++) { for (j = 0; j < num_clients; j++) { thread_spawn( &client_id[(i*num_clients) + j], client, (void *) (long) i); } } /* Wait for servers to complete */ for (i = 0; i < num_servers; i++) { thread_join(&server_id[i]); } gettimeofday(&endtv, NULL); if (verbose) printf("all servers complete: waiting for clients...\n"); for (i = 0; i < totalclients; i++) { thread_join(&client_id[i]); } /* report results */ deltatv.tv_sec = endtv.tv_sec - starttv.tv_sec; deltatv.tv_usec = endtv.tv_usec - starttv.tv_usec; if (endtv.tv_usec < starttv.tv_usec) { deltatv.tv_sec--; deltatv.tv_usec += 1000000; } double dsecs = (double) deltatv.tv_sec + 1.0E-6 * (double) deltatv.tv_usec; printf(" in %lu.%03u seconds\n", deltatv.tv_sec, deltatv.tv_usec/1000); printf(" throughput in messages/sec: %g\n", (double)totalmsg / dsecs); printf(" average message latency (usec): %2.3g\n", dsecs * 1.0E6 / (double) totalmsg); double time_in_sec = (double)deltatv.tv_sec + (double)deltatv.tv_usec/1000.0; double throughput_msg_p_sec = (double) totalmsg/dsecs; double avg_msg_latency = dsecs*1.0E6 / (double)totalmsg; if (save_perfdata == TRUE) { record_perf_data("mpmm_avg_msg_latency", "usec", avg_msg_latency, "Message latency measured in microseconds. Lower is better", stderr); } if (stress_prepost) { int64_t sendns = abs_to_ns(g_client_send_time); dsecs = (double)sendns / (double)NSEC_PER_SEC; printf(" total send time: %2.3gs\n", dsecs); printf(" average send time (usec): %2.3g\n", dsecs * 1.0E6 / (double)totalmsg); } return (0); }
void ThreadedSSLSocketInitiator::doConnect(const SessionID &s, const Dictionary &d) { try { Session *session = Session::lookupSession(s); if (!session->isSessionTime(UtcTimeStamp())) return; Log *log = session->getLog(); std::string address; short port = 0; getHost(s, d, address, port); int socket = socket_createConnector(); if (m_noDelay) socket_setsockopt(socket, TCP_NODELAY); if (m_sendBufSize) socket_setsockopt(socket, SO_SNDBUF, m_sendBufSize); if (m_rcvBufSize) socket_setsockopt(socket, SO_RCVBUF, m_rcvBufSize); setPending(s); log->onEvent("Connecting to " + address + " on port " + IntConvertor::convert((unsigned short)port)); SSL *ssl = SSL_new(m_ctx); if (ssl == 0) { log->onEvent("Failed to create ssl object"); return; } SSL_clear(ssl); BIO *sbio = BIO_new_socket(socket, BIO_CLOSE); SSL_set_bio(ssl, sbio, sbio); ThreadedSSLSocketConnection *pConnection = new ThreadedSSLSocketConnection( s, socket, ssl, address, port, getLog()); ThreadPair *pair = new ThreadPair(this, pConnection); { Locker l(m_mutex); thread_id thread; if (thread_spawn(&socketThread, pair, thread)) { addThread(SocketKey(socket, ssl), thread); } else { delete pair; pConnection->disconnect(); delete pConnection; SSL_free(ssl); setDisconnected(s); } } } catch (std::exception &) { } }
int main(int argc, const char *argv[]) { int base_src_port = 65500; int polling = 0; int busy_poll = 0; int packet_timestamp = 0; static struct option long_options[] = { {"src-port", required_argument, 0, 's'}, {"polling", no_argument, 0, 'p'}, {"busy-poll", required_argument, 0, 'b'}, {"timestamp", no_argument, 0, 't'}, {NULL, 0, 0, 0}}; const char *optstring = optstring_from_long_options(long_options); optind = 1; while (1) { int option_index = 0; int arg = getopt_long(argc, (char **)argv, optstring, long_options, &option_index); if (arg == -1) { break; } switch (arg) { case 's': base_src_port = atoi(optarg); break; case 'p': polling = 1; break; case 'b': busy_poll = atoi(optarg); break; case 't': packet_timestamp = 1; break; default: FATAL("Unknown option %c: %s", arg, argv[optind]); } } int thread_num = argc - optind; if (thread_num < 1) { FATAL("Usage: %s [--polling] [--busy-poll=<>] [--src-port=<>] " "[--timestamp] [target:port...]", argv[0]); } struct net_addr *target_addrs = calloc(thread_num, sizeof(struct net_addr)); int t; for (t = 0; t < thread_num; t++) { const char *target_addr_str = argv[optind + t]; parse_addr(&target_addrs[t], target_addr_str); fprintf(stderr, "[*] Sending to %s, polling=%i, src_port=%i\n", addr_to_str(&target_addrs[t]), polling, base_src_port + t); } struct state *array_of_states = calloc(thread_num, sizeof(struct state)); for (t = 0; t < thread_num; t++) { struct state *state = &array_of_states[t]; state->target_addr = &target_addrs[t]; state->polling = polling; state->busy_poll = busy_poll; if (base_src_port > 0) { state->src_port = base_src_port + t; } thread_spawn(thread_loop, state); } while (1) { struct timeval timeout = NSEC_TIMEVAL(MSEC_NSEC(1000UL)); while (1) { int r = select(0, NULL, NULL, NULL, &timeout); if (r != 0) { continue; } if (TIMEVAL_NSEC(&timeout) == 0) { break; } } for (t = 0; t < thread_num; t++) { struct state *state = &array_of_states[t]; uint64_t pps; double avg, stddev; double avg_packet, stddev_packet; pthread_spin_lock(&state->lock); stddev_get(&state->stddev, &pps, &avg, &stddev); int min = state->stddev.min; stddev_get(&state->stddev_packet, NULL, &avg_packet, &stddev_packet); stddev_init(&state->stddev); stddev_init(&state->stddev_packet); pthread_spin_unlock(&state->lock); printf("pps=%6lu avg=%7.3fus dev=%7.3fus min=%6.3fus ", pps, avg / 1000., stddev / 1000., (double)min / 1000.); if (packet_timestamp) { printf("(packet=%5.3fus/%5.3f) ", avg_packet / 1000., stddev_packet / 1000.); } } printf("\n"); } return 0; }
void syscall_ipc_send(cpu_int_state_t *state) { // Extract arguments uint32_t pid = (uint32_t) state->state.rdi; uint16_t flags = (uint32_t) state->state.rbx; uint32_t length = (uint32_t) state->state.rcx; // Check if process exists process_t *process_target = (pid == process_current->pid) ? process_current : process_get(pid); if (0 == process_target) SYSCALL_RETURN_ERROR(1); // Check handler if (0 == process_target->message_handler) SYSCALL_RETURN_ERROR(2); // Check buffer size if (length > thread_current->ipc_buffer_sz[IPC_BUFFER_SEND]) SYSCALL_RETURN_ERROR(3); // Spawn handler thread thread_t *handler = thread_spawn( process_target, process_target->message_handler); // Set thread role ipc_role_ctx_t *role_ctx = (ipc_role_ctx_t *) heap_alloc(sizeof(ipc_role_ctx_t)); role_ctx->flags = flags; role_ctx->sender_process = process_current->pid; role_ctx->sender_thread = thread_current->tid; handler->role = THREAD_ROLE_IPC_RECEIVER; handler->role_ctx = role_ctx; // Move buffer to handler thread if (length > 0) ipc_buffer_move( thread_current, IPC_BUFFER_SEND, handler, IPC_BUFFER_RECV, process_target); // Write header to registers ipc_message_header( IPC_BUFFER_RECV, length, flags, process_current->pid, handler->tid, &handler->state); // Freeze the invoking thread, if a response is expected if (0 == (flags & IPC_FLAG_IGNORE_RESPONSE)) thread_freeze(thread_current); // Switch to handler thread thread_switch(handler, state); }