/* _signal_handler - Process daemon-wide signals */ static void *_signal_handler(void *no_data) { int rc, sig; int sig_array[] = {SIGINT, SIGTERM, SIGHUP, SIGABRT, 0}; sigset_t set; (void) pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); (void) pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); /* Make sure no required signals are ignored (possibly inherited) */ _default_sigaction(SIGINT); _default_sigaction(SIGTERM); _default_sigaction(SIGHUP); _default_sigaction(SIGABRT); while (1) { xsignal_sigset_create(sig_array, &set); rc = sigwait(&set, &sig); if (rc == EINTR) continue; switch (sig) { case SIGHUP: /* kill -1 */ info("Reconfigure signal (SIGHUP) received"); reconfig(); break; case SIGINT: /* kill -2 or <CTRL-C> */ case SIGTERM: /* kill -15 */ info("Terminate signal (SIGINT or SIGTERM) received"); shutdown_threads(); return NULL; /* Normal termination */ case SIGABRT: /* abort */ info("SIGABRT received"); abort(); /* Should terminate here */ shutdown_threads(); return NULL; default: error("Invalid signal (%d) received", sig); } } }
AREXPORT void * ArRecurrentTask::runThread(void *ptr) { threadStarted(); #ifndef WIN32 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL); #endif while (myRunning) { bool doit; while (myRunning) { lock(); doit = go_req; unlock(); if (doit) break; // yield(); // don't hog resources #ifndef WIN32 usleep(10000); #else Sleep(10); #endif } if (!myRunning) break; lock(); go_req = false; running = true; // we've been requested to go unlock(); task(); // do what we've got to do... lock(); running = false; // say we're done unlock(); } threadFinished(); return NULL; }
// On entry, cancellation ought be disabled, and execution restricted to a // single processor via hard affinity settings (FIXME: verify?). static void * thread(void *void_marshal){ tguard *marshal = void_marshal; evhandler *ev = NULL; torque_ctx *ctx; ctx = marshal->ctx; if(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL)){ goto earlyerr; } if((ev = create_evhandler(&ctx->evq,&marshal->stack)) == NULL){ goto earlyerr; } if(pthread_mutex_lock(&marshal->lock)){ destroy_evhandler(ctx,ev); goto earlyerr; } if(marshal->ctx->ev == NULL){ marshal->ctx->ev = ev; }else{ ev->nexttid = marshal->ctx->ev->nexttid; } marshal->ctx->ev->nexttid = pthread_self(); marshal->status = THREAD_STARTED; pthread_cond_broadcast(&marshal->cond); pthread_mutex_unlock(&marshal->lock); // After this point, anything we wish to use from marshal must've been // copied onto our own stack (hence broadcasting prior to unlocking). event_thread(ctx,ev); // Should never reach here (event_thread() is marked ((noreturn))) destroy_evhandler(ctx,ev); return NULL; earlyerr: pthread_mutex_lock(&marshal->lock); // continue regardless marshal->status = THREAD_PREFAIL; pthread_cond_broadcast(&marshal->cond); pthread_mutex_unlock(&marshal->lock); destroy_evhandler(ctx,ev); return NULL; }
// --------------------------------------------------------------------------- // void *renderThreadLoop (void *data) { wdTimers[WD_RENDER] = time (0); pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0); int ptErr = 0; for (;;) { LOCK (windowList.lock, ptErr); if (ptErr) die ("Error locking mutex"); processWindows (); UNLOCK (windowList.lock, ptErr); if (ptErr) die ("Error unlocking mutex"); wdTimers[WD_RENDER] = time (0); sleep (ctaConfig.arrLen); } }
void* GRSServer::sendRoomService(void* obj){ pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); GRSServer *tempgr=(GRSServer *)obj; UdpServer *temp=tempgr->udps; string tis=tempgr->localName; tis.append("的房间"); while (true) { pthread_testcancel(); int res; char tbuffer[8]; sockaddr_in remoteRecAddr; if ((res=temp->recvMsg(tbuffer,8,&remoteRecAddr))>0) { const char* sa=inet_ntoa(remoteRecAddr.sin_addr); string temps=tbuffer; const char* s=tis.c_str(); temp->sendMsg(sa,s); } } return NULL; }
/* The main service loop. It uses poll() to find things to act upon. */ void run_service (void) { int i; int polled; cbfree = NULL; errno = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, NULL); if (errno) { tlog (TLOG_UNIXSOCK | TLOG_DAEMON, LOG_ERR, "Service routine thread cancellability refused"); exit (1); } for (i=0; i<1024; i++) { cblist [i].next = cbfree; cblist [i].fd = -1; // Mark as unused pthread_cond_init (&cblist [i].semaphore, NULL); cblist [i].followup = NULL; cbfree = &cblist [i]; } tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Polling %d sockets numbered %d, %d, %d, ...", num_sox, soxpoll [0].fd, soxpoll [1].fd, soxpoll [2].fd); while (polled = poll (soxpoll, num_sox, -1), polled > 0) { tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Polled %d sockets, returned %d", num_sox, polled); for (i=0; i<num_sox; i++) { if (soxpoll [i].revents & (POLLHUP|POLLERR|POLLNVAL)) { int sox = soxpoll [i].fd; tlog (TLOG_UNIXSOCK, LOG_NOTICE, "Unregistering socket %d", sox); unregister_client_socket_byindex (i); close (sox); continue; } else if (soxpoll [i].revents) { tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Socket %d has revents=%d", soxpoll [i].fd, soxpoll [i].revents); process_activity (soxpoll [i].fd, i, &soxinfo [i], soxpoll [i].revents); } } tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Polling %d sockets numbered %d, %d, %d, ...", num_sox, soxpoll [0].fd, soxpoll [1].fd, soxpoll [2].fd); } if (stop_service) { tlog (TLOG_UNIXSOCK, LOG_NOTICE, "Service hangup in response to request"); } else { tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Polled %d sockets, returned %d", num_sox, polled); perror ("Failed to poll for activity"); } }
void* ThreadProc(void* param) #endif { PSnapThread Thread; // Unix but not Solaris #if (defined(POSIX) || defined(OS_OSX)) && (!defined(OS_SOLARIS)) int last_type, last_state; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &last_type); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &last_state); #endif #ifdef OS_SOLARIS #endif Thread = PSnapThread(param); if (!Thread->Terminated) try { Thread->Execute(); } catch (...) { }; Thread->Closed = true; if (Thread->FreeOnTerminate) { delete Thread; }; #ifdef OS_WINDOWS ExitThread(0); #endif #if defined(POSIX) && (!defined(OS_SOLARIS)) pthread_exit((void*)0); #endif #if defined(OS_OSX) pthread_exit((void*)0); #endif #ifdef OS_SOLARIS thr_exit((void*)0); #endif return 0; // never reach, only to avoid compiler warning }
// funzione realtiva allo spinlock void *do_something(long int who_i_am) { int i; int dummy; // imposta la cancellazione asincrona pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&dummy); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&dummy); // aspetta che pure l'altro thread l'abbia fatto pthread_barrier_wait(&pbarrier); // sblocca il segnale SIGUSR1 pthread_sigmask(SIG_UNBLOCK,&block_sig,NULL); while (1) { // selezione un intervallo casuale di tempo i=rand()%9+1; // avvisa printf("Thread %ld: going to sleep for %d sec...\n",who_i_am,i); // e dormi sleep(i); // prova ad acquisire lo spinlock if (pthread_spin_trylock(&spinlock)) { // in caso contrario avvisa printf("Thread %ld: wait for the spinlock...\n",who_i_am); // e attendi pthread_spin_lock(&spinlock); } // da qui ho acquisito lo spinlock // seleziona un intervallo casuale di tempo i=rand()%9+1; // avvisa printf("Thread %ld: spinlock obtained and now wait for %d sec...\n",who_i_am,i); // e dormi sleep(i); printf("Thread %ld: unlock spinlock...\n",who_i_am); // rilascia lo spinlock pthread_spin_unlock(&spinlock); } return NULL; }
static void *_start_routine(void *arg) { thread_start_t *start = (thread_start_t *)arg; void *(*start_routine)(void *) = start->start_routine; void *real_arg = start->arg; thread_type *thread = start->thread; int detach = start->detached; _block_signals(); free(start); /* insert thread into thread tree here */ _mutex_lock(&_threadtree_mutex); thread->sys_thread = pthread_self(); avl_insert(_threadtree, (void *)thread); _mutex_unlock(&_threadtree_mutex); #ifdef THREAD_DEBUG LOG_INFO4("Added thread %d [%s] started at [%s:%d]", thread->thread_id, thread->name, thread->file, thread->line); #endif if (detach) { pthread_detach(thread->sys_thread); thread->detached = 1; } pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); /* call the real start_routine and start the thread ** this should never exit! */ (start_routine)(real_arg); #ifdef THREAD_DEBUG LOG_WARN("Thread x should never exit from here!!!"); #endif return NULL; }
static void* threadEntrypoint(void* aArg) { #ifndef __ANDROID__ int oldState; int status; #endif ThreadData* data = (ThreadData*)aArg; assert(data != NULL); #ifdef ATTEMPT_THREAD_PRIORITIES { TInt platMin = sched_get_priority_min(kThreadSchedPolicy); TInt platMax = sched_get_priority_max(kThreadSchedPolicy); // convert the UPnP library's 50 - 150 priority range into // an equivalent posix priority // ...calculate priority as percentage of library range int32_t percent = (((int32_t )data->iPriority - 50) * 100) / (150 - 50); // ...calculate native priority as 'percent' through the dest range int32_t priority = platMin + ((percent * (platMax - platMin))/100); sched_param param; param.sched_priority = priority; int status = pthread_setschedparam(data->iThread, kThreadSchedPolicy, ¶m); assert(status == 0); } #endif // ATTEMPT_THREAD_PRIORITIES // Disable cancellation - we're in a C++ environment, and // don't want to rely on pthreads to mess things up for us. #ifndef __ANDROID__ status = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldState); assert(status == 0); #endif //tlsThreadArg = data->iArg; pthread_setspecific(gThreadArgKey, data->iArg); data->iEntryPoint(data->iArg); return NULL; }
static void * th_wait(void *arg) { proc_wt_t *wt = (proc_wt_t *)arg; pid_t w; int status; //pthread_cleanup_push(kill_pid, wt); status = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); if (status != 0) printf("pthread_setcancelstate %d\n", status); do { w = waitpid(wt->pid, &status, WUNTRACED | WCONTINUED); if (w == -1) { wt->status |= PROC_S_ERR; perror("waitpid"); goto out; } if (WIFEXITED(status)) { wt->status |= PROC_S_EXITED; printf("exited, status=%d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { wt->status |= PROC_S_SIGNALED; printf("killed by signal %d\n", WTERMSIG(status)); } else if (WIFSTOPPED(status)) { printf("stopped by signal %d\n", WSTOPSIG(status)); } else if (WIFCONTINUED(status)) { printf("continued\n"); } } while (!WIFEXITED(status) && !WIFSIGNALED(status)); out: pthread_cancel(wt->thr_timeout); //pthread_cleanup_pop(0); return NULL; }
/* Function that the thread executes upon its creation */ void *a_thread_func() { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); pthread_cleanup_push(a_cleanup_func,NULL); /* Indicate to main() that the thread has been created. */ sem1=INMAIN; /* Wait until main() has sent out a cancel request, meaning until it * sets sem1==INMAIN. Sleeping for 3 secs. to give time for the * cancel request to be sent and processed. */ while (sem1==INMAIN) sleep(1); /* Should reach here if the thread correctly ignores the cancel * request. */ pthread_cleanup_pop(0); cleanup_flag=1; pthread_exit(0); return NULL; }
void *pthread_1st(void *arg) { #if 0 int oldstate; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate); if(oldstate == PTHREAD_CANCEL_ENABLE) printf("it is enable before...\n"); #endif #if 0 int oldtype; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype); if(oldtype == PTHREAD_CANCEL_DEFERRED) printf("it is deferrred...\n"); #endif pthread_cleanup_push(cleanup_handle, NULL); //printf("%s(): The first thread...\n", __FUNCTION__); //fflush(stdout); while(1) { if(i == (2^32)/2-1) break; //printf("%s(): i %d\n", __FUNCTION__, i); //fflush(stdout); i++; } //sleep(1); //return; //pthread_testcancel(); printf("I will exit...\n"); fflush(stdout); pthread_exit((void *)22); pthread_cleanup_pop(0); //exit(1); }
lagopus_result_t lagopus_rwlock_leave_critical(lagopus_rwlock_t *rwlptr) { lagopus_result_t ret = LAGOPUS_RESULT_ANY_FAILURES; if (rwlptr != NULL && *rwlptr != NULL) { int st; int oldstate; /* * The caller must have this rwlock locked. */ oldstate = (*rwlptr)->m_prev_cancel_state; if (oldstate == PTHREAD_CANCEL_ENABLE || oldstate == PTHREAD_CANCEL_DISABLE) { /* * This rwlock is locked via lagopus_rwlock_enter_critical(). */ if ((st = pthread_rwlock_unlock(&((*rwlptr)->m_rwl))) == 0) { if ((st = pthread_setcancelstate(oldstate, NULL)) == 0) { ret = LAGOPUS_RESULT_OK; pthread_testcancel(); } else { errno = st; ret = LAGOPUS_RESULT_POSIX_API_ERROR; } } else { errno = st; ret = LAGOPUS_RESULT_POSIX_API_ERROR; } } else { ret = LAGOPUS_RESULT_CRITICAL_REGION_NOT_OPENED; } } else { ret = LAGOPUS_RESULT_INVALID_ARGS; } return ret; }
/*-------------------------------------------------------------------------- * NAME * H5TS_cancel_count_inc * * USAGE * H5TS_cancel_count_inc() * * RETURNS * 0 on success non-zero error code on error. * * DESCRIPTION * Creates a cancelation counter for a thread if it is the first time * the thread is entering the library. * * if counter value is zero, then set cancelability type of the thread * to PTHREAD_CANCEL_DISABLE as thread is entering the library and store * the previous cancelability type into cancelation counter. * Increase the counter value by 1. * * PROGRAMMER: Chee Wai LEE * May 2, 2000 * * MODIFICATIONS: * * 19 May 2000, Bill Wendling * Changed function to return a value. Also changed the malloc() call to * the H5MM_malloc() call and checked the returned pointer. * *-------------------------------------------------------------------------- */ herr_t H5TS_cancel_count_inc(void) { #ifdef H5_HAVE_WIN_THREADS /* unsupported; just return 0 */ return SUCCEED; #else /* H5_HAVE_WIN_THREADS */ H5TS_cancel_t *cancel_counter; herr_t ret_value = SUCCEED; cancel_counter = (H5TS_cancel_t *)H5TS_get_thread_local_value(H5TS_cancel_key_g); if (!cancel_counter) { /* * First time thread calls library - create new counter and associate * with key */ cancel_counter = (H5TS_cancel_t *)H5MM_calloc(sizeof(H5TS_cancel_t)); if (!cancel_counter) { H5E_push_stack(NULL, "H5TS_cancel_count_inc", __FILE__, __LINE__, H5E_ERR_CLS_g, H5E_RESOURCE, H5E_NOSPACE, "memory allocation failed"); return FAIL; } ret_value = pthread_setspecific(H5TS_cancel_key_g, (void *)cancel_counter); } if (cancel_counter->cancel_count == 0) /* thread entering library */ ret_value = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_counter->previous_state); ++cancel_counter->cancel_count; return ret_value; #endif /* H5_HAVE_WIN_THREADS */ }
void* LaunchThreadBalanceLength(void* p_data) { /* Set up thread-safe buffers for this new thread */ LOG.AddThreadSafeBuffer(); LOGERR.AddThreadSafeBuffer(); /* Make this thread cancellable */ pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); /* Get a handle to the thread launch data */ CSpaceMultiThreadBalanceLength::SThreadLaunchData* psData = reinterpret_cast<CSpaceMultiThreadBalanceLength::SThreadLaunchData*>(p_data); /* Create cancellation data */ SCleanupThreadData sCancelData; sCancelData.StartSenseControlPhaseMutex = &(psData->Space->m_tStartSenseControlPhaseMutex); sCancelData.StartActPhaseMutex = &(psData->Space->m_tStartActPhaseMutex); sCancelData.StartPhysicsPhaseMutex = &(psData->Space->m_tStartPhysicsPhaseMutex); sCancelData.StartMediaPhaseMutex = &(psData->Space->m_tStartMediaPhaseMutex); sCancelData.FetchTaskMutex = &(psData->Space->m_tFetchTaskMutex); pthread_cleanup_push(CleanupThread, &sCancelData); psData->Space->SlaveThread(); /* Dispose of cancellation data */ pthread_cleanup_pop(1); return NULL; }
void *run_com(void *arg) { char response[512]; char **tab = NULL; int size; memset(response, 0, 1024); fprintf(stderr, "thread com demarre :\n"); /*--------------Blocquer les signaux------------------*/ sigset_t mask; sigfillset(&mask); pthread_sigmask(SIG_SETMASK, &mask, NULL); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); while (TRUE) { read_response(sc, response); fprintf(stderr, "com: recu reponse len %zu : %s\n", strlen(response), response); if (0 == strlen(response)) { fprintf(stderr, "ERROR : Connection Socket"); erreur("ERROR : Connection Socket", TRUE); break; } tab = string_to_arraystring(response, &size, '/'); traitement(tab, size); /*free resources*/ free_table(tab, size); memset(response, 0, sizeof(response)); } pthread_cancel(thread_chat); //TODO return NULL; }
static void * tf1 (void *p) { int err; if (pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL) != 0 || pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, NULL) != 0) { puts ("cannot set cancellation options"); exit (1); } err = pthread_mutex_lock (&mut); if (err != 0) { puts ("child: cannot get mutex"); exit (1); } err = pthread_barrier_wait (&bar); if (err != 0 && err != PTHREAD_BARRIER_SERIAL_THREAD) { printf ("barrier_wait returned %d\n", err); exit (1); } puts ("child: got mutex; waiting"); pthread_cleanup_push (ch, NULL); pthread_cond_wait (&cond, &mut); pthread_cleanup_pop (0); puts ("child: cond_wait should not have returned"); return NULL; }
// Relay output from pru to stdout void* receive(void* param) { int* val; int ready; FILE* output; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); val = (int*)param; //stupid, but compiler unhappy without this output = (FILE*)*val; if ((int)output == 1) output = stdout; // loop looking for output from pruss for(;;){ ready = pruSharedMem_int[FROMPRU_F]; if (ready != 0x00) { // check for special signal from pruss indicating a (re)start if (ready == 0x89abcdef) { if (quiet_mode) { fprintf(output, "reset\n"); } else { fprintf(output, "Reset: %#8x\n", pruSharedMem_int[FROMPRU]); } } else { if (quiet_mode) { fprintf(output, "%#8x\n", pruSharedMem_int[FROMPRU]); } else { fprintf(output, "Got: %#8x\n", pruSharedMem_int[FROMPRU]); } } // acknowledge message pruSharedMem_int[FROMPRU_F] = 0x00; } // don't use all our cpu cycles usleep(RECEIVE_SLEEP); } pthread_exit(NULL); }
static void *limitMonitorTh(void *_) { struct rusage usg; int peak_mem; float elapsed; // Enable cancelability and enable cancelation in sleep() call pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); while (1){ borTimerStop(&limit_monitor.timer); elapsed = borTimerElapsedInSF(&limit_monitor.timer); if ((int)elapsed > limit_monitor.max_time){ fprintf(stderr, "Aborting due to exceeded hard time limit" " (elapsed %f, limit: %d.\n", elapsed, limit_monitor.max_time); fflush(stderr); limitMonitorAbort(); break; } if (getrusage(RUSAGE_SELF, &usg) == 0){ peak_mem = usg.ru_maxrss / 1024L; if (peak_mem > limit_monitor.max_mem){ fprintf(stderr, "Aborting due to exceeded hard mem limit" " (peak-mem: %d, limit: %d).\n", peak_mem, limit_monitor.max_mem); fflush(stderr); limitMonitorAbort(); break; } } sleep(limit_monitor.sleeptime); } return NULL; }
static void *jk_thread_loop(void *arg) { jk_thread_pool_t *thd = arg; jk_thread_task_t *tsk; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); pthread_mutex_lock(&thd->wait_lock); thd->wait_threads--; pthread_cond_signal(&thd->wait_cond); pthread_mutex_unlock(&thd->wait_lock); while (1) { pthread_mutex_lock(&thd->lock); while (thd->task_nums <= 0) { pthread_cond_wait(&thd->cond, &thd->lock); /* Here maybe destroy */ } /* Get lock here */ tsk = thd->wait_tasks; thd->wait_tasks = tsk->next; thd->task_nums--; pthread_mutex_unlock(&thd->lock); tsk->call(tsk->arg); if (tsk->finish) { tsk->finish(tsk->arg); } free(tsk); } return NULL; }
void Consumer::Setup() { // Do any setup here // 不允许pthread_cancel机制取消,使用自定义标志位取消机制 int code = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); if (code!=0) { MCE_INFO("Error ("<<strerror(code)<<") pthread_setcancelstate in Thread::Start!"); } //// 允许取消:收到cancel信号后设为cancle态 //int code = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); //if (code!=0) //{ // fprintf(stderr, "Error (%s) pthread_setcancelstate in Thread::Start!\n", strerror(code)); //} //// 收到cancel信号后推迟到取消点处理 //code = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); //if(code != 0) //{ // fprintf(stderr, "Error (%s) pthread_setcanceltype in Thread::Start!\n", strerror(code)); //} }
void *thread_func(__unused void *arg) { int cancel_state, cancel_type; printf("PTHREAD_CANCEL_ENABLE = %d\nPTHREAD_CANCEL_DISABLE = %d\n", PTHREAD_CANCEL_ENABLE, PTHREAD_CANCEL_DISABLE); printf("PTHREAD_CANCEL_ASYNCHRONOUS = %d\nPTHREAD_CANCEL_DEFERRED = %d\n", PTHREAD_CANCEL_ASYNCHRONOUS, PTHREAD_CANCEL_DEFERRED); // default value = ENABLE if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &cancel_state) != 0) perror("setcancelstate"); // default value = DEFERRED if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &cancel_type) != 0) perror("setcanceltype"); printf("old_cancel_state = %d\nold_cancel_type = %d\n", cancel_state, cancel_type); // cancelation point sleep(10); return arg; }
void* thread_01(void* num) { int i, n; pthread_cleanup_push(thread_cleanup, num); errno = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); test_errno("pthread_setcancelstate"); errno = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); test_errno("pthread_setcanceltype"); printf("thread #%d (PTHREAD_CANCEL_ASYNCHRONOUS)\n", (int)(size_t)num); while (1) { n = 1000000; for (i=0; i < n; i++); } pthread_cleanup_pop(1); return NULL; }
void * ThreadLinux::StaticThreadFunction( void * p_pParam ) { // Make the thread cancelable. pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL ); // Get the thread from the param ThreadLinux * pThread = reinterpret_cast< ThreadLinux * >( p_pParam ); // Mark the thread as running pThread->m_Mutex.Lock( ); pThread->m_Running = true; pThread->m_Mutex.Unlock( ); // Run the thread function and get the return value. pThread->m_Function( ); // Mark the thread as not pThread->m_Mutex.Lock( ); pThread->m_Running = false; pThread->m_Mutex.Unlock( ); return NULL; }
void tc_gc(void *data) { struct timespec ts; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); while (true) { if (pthread_mutex_lock(&gc_mutex) != 0) continue; pthread_cond_timedwait(&gc_cond, &gc_mutex, future_time(&ts, tc_gc_sleep)); debug("tc_gc: ENTER THE COLLECTOR!!"); // always wanted to say that metadata_free_unused_tc_dir(); pthread_mutex_unlock(&gc_mutex); pthread_testcancel(); } debug("gc loop exited"); }
void *thread_function(void *arg) { int i, res; res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); if (res != 0) { perror("thread pthread_setcancelstate failed"); exit(EXIT_FAILURE); } res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); if (res != 0) { perror("thread pthread_setcanceltype failed"); exit(EXIT_FAILURE); } printf("thread_function is still running\n"); for (i = 0; i < 10; ++i) { printf("thread is still running (%d)......\n", i); sleep(1); } printf("I'am still running\n"); pthread_exit(0); }
/** * Initlize thread (+sigmask) */ static inline void tpool_thread_init(struct tpool_thread *t) { sigset_t set; // detach first pthread_detach(t->tid); // block all signal except for: SIGFPE/SIGILL/SIGBUS/SIGSEGV sigfillset(&set); sigdelset(&set, SIGFPE); sigdelset(&set, SIGILL); sigdelset(&set, SIGBUS); sigdelset(&set, SIGSEGV); pthread_sigmask(SIG_SETMASK, &set, NULL); // only can be canceled on executing task pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); // init some struct members t->status |= TPOOL_THREAD_BUSY; t->calls = 0; }
/* * _thread_ipmi_run is the thread calling ipmi and launching _thread_ipmi_write */ static void *_thread_ipmi_run(void *no_data) { // need input (attr) int time_lost; (void) pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); (void) pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); flag_energy_accounting_shutdown = false; if (debug_flags & DEBUG_FLAG_ENERGY) info("ipmi-thread: launched"); slurm_mutex_lock(&ipmi_mutex); if (_thread_init() != SLURM_SUCCESS) { if (debug_flags & DEBUG_FLAG_ENERGY) info("ipmi-thread: aborted"); slurm_mutex_unlock(&ipmi_mutex); return NULL; } slurm_mutex_unlock(&ipmi_mutex); flag_thread_started = true; //loop until slurm stop while (!flag_energy_accounting_shutdown) { time_lost = (int)(time(NULL) - last_update_time); _task_sleep(slurm_ipmi_conf.freq - time_lost); slurm_mutex_lock(&ipmi_mutex); _thread_update_node_energy(); slurm_mutex_unlock(&ipmi_mutex); } if (debug_flags & DEBUG_FLAG_ENERGY) info("ipmi-thread: ended"); return NULL; }
void * tc_helper_thread(void *t_context) { int rc = 0; struct thread_context *tctx = (struct thread_context *)t_context; int old_state, old_type; rc = pthread_mutex_lock(&tctx->helper_mutex); if (rc) { printf("%s: pthread_mutex_lock failed with rc = %d, errno = %d \n", rc, errno); pthread_exit(&rc); } /* notify main thread to proceed creating other master thread */ rc = pthread_cond_broadcast(&tctx->helper_cond); if (rc) { printf(" %s: pthread_cond_broadcast failed with rc = %d, errno = %d \n", __FUNCTION__, rc, errno); pthread_exit(&rc); } rc = pthread_mutex_unlock(&tctx->helper_mutex); if (rc) { printf(" %s: pthread_mutex_unlock failed failed with rc = %d, errno = %d \n", __FUNCTION__, rc, errno); pthread_exit(&rc); } pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type); /* creates a cancellation point in the calling thread */ pthread_testcancel(); rc = recv_arp_reply(tctx); if(rc) { printf("Error recv packets on interface %s, errno = %d \n", &tctx->source.name, errno); } pthread_exit(&rc); }