/** * Set scheduling policy and parameters of a thread. * @param thread The target thread. * @param policy Ignored. * @param param The thread scheduling priority. * @return If the function succeeds, the return value is 0. * If the function fails, the return value is -1, * with errno set to indicate the error (ESRCH). */ int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param) { if (param != NULL) return pthread_setschedprio(thread, param->sched_priority); return 0; }
CPhotoSpriteLoader::CPhotoSpriteLoader(char * Folder, char * PhotoFolder, pthread_mutex_t * LockDraw, CConfig * Config) { _LockDraw = LockDraw; _Status = 0; _LastUpdate = 0; _XMLFileName = new char[strlen(PhotoFolder) + 11]; sprintf(_XMLFileName, "%s/fotki.xml", PhotoFolder); _Folder = Folder; _PhotoFolder = PhotoFolder; _DownloadFolder = new char[strlen(PhotoFolder) + 7]; sprintf(_DownloadFolder, "%s/.temp", PhotoFolder); mkdir(_DownloadFolder, S_IRWXU | S_IRWXG | S_IREAD); _FileNames = new CFileNames(PhotoFolder); _HTTP = new CHTTP; pthread_mutex_init(&_LockPhotoSpriteQueue, NULL); pthread_mutex_init(&_LockStatus, NULL); _Config = Config; pthread_create(&_pThrFillQueue, NULL, CPhotoSpriteLoader::_ThrFillQueue, this); pthread_detach(_pThrFillQueue); pthread_setschedprio(_pThrFillQueue, 10); }
void pixie_cpu_raise_priority(void) { #if defined WIN32 DWORD_PTR result; result = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); if (result == 0) { fprintf(stderr, "set_priority: returned error win32:%u\n", (unsigned)GetLastError()); } #elif defined(__linux__) && defined(__GNUC__) pthread_t thread = pthread_self(); pthread_attr_t thAttr; int policy = 0; int max_prio_for_policy = 0; pthread_attr_init(&thAttr); pthread_attr_getschedpolicy(&thAttr, &policy); max_prio_for_policy = sched_get_priority_max(policy); pthread_setschedprio(thread, max_prio_for_policy); pthread_attr_destroy(&thAttr); return; #endif }
int main(void) { OS_ERR err; int i; HAL_Init(); /* See Note 1. */ Mem_Init(); /* Initialize Memory Managment Module */ Math_Init(); /* Initialize Mathematical Module */ BSP_IntDisAll(); /* Disable all Interrupts. */ App_OS_SetAllHooks(); OSInit(&err); /* Init uC/OS-III. */ for(i = 0; i < APP_THREAD_COUNT-1; i++) sem_init(&g_thread_startup[i], 0, 0); sem_init(&g_sem_debug, 0, 1); g_debug_tx_buffer = mq_open(0, 512); pthread_attr_setstacksize(&g_thread_attr[0], 1024*2); pthread_create(&g_thread[0], &g_thread_attr[0], Thread_Startup, 0); pthread_setschedprio(&g_thread[0], 1); DEFINE_THREAD(Thread_DebugTX, 1024, 1); DEFINE_THREAD(Thread_DebugRx, 1024, 1); DEFINE_THREAD(Thread_RFIntr, 1024, 3); DEFINE_THREAD(Thread_MiwiTask,1024*5, 4); OSStart(&err); /* Start multitasking (i.e. give control to uC/OS-III). */ while (1) {} }
/////////////////////////////////////////////////////////////////////////////// /// \brief starts the processing thread and sets priority to max /// void InputHandler :: start () { pthread_attr_t attr ; pthread_attr_init ( &attr ) ; int policy = 0 ; int max_prio_for_policy = 0 ; pthread_attr_getschedpolicy ( &attr , &policy ) ; max_prio_for_policy = sched_get_priority_max ( policy ) ; glob_t globbuf ; glob ( "/dev/input/event*" , GLOB_TILDE , NULL , &globbuf ) ; printf ( "number of events found %d\n" , ( int ) globbuf . gl_pathc ) ; for ( unsigned int loop = 0 ; loop < globbuf . gl_pathc ; ++loop ) { if ( isValidInputEventFile ( globbuf . gl_pathv [ loop ] ) ) { std :: string *filename = new std :: string ( globbuf . gl_pathv [ loop ] ) ; rt_printf ( "InputHandler starting thread: %s\n" , filename -> c_str () ) ; pthread_create ( &thread , NULL , ( void* (*) ( void*) ) ( thread_func ) , filename ) ; pthread_setschedprio ( thread , max_prio_for_policy ) ; pthread_attr_destroy ( &attr ) ; } } }
void Thread::setPriority(Thread::ThreadPriority p) { if(getuid() == 0) { priority_ = p; pthread_setschedprio(threadId_, (static_cast<int>(priority_))); } }
void Thread::SetPriority(int priority) { #ifdef WIN32 if (handle_) SetThreadPriority((HANDLE)handle_, priority); #endif #if defined(__linux__) && !defined(ANDROID) pthread_t* thread = (pthread_t*)handle_; if (thread) pthread_setschedprio(*thread, priority); #endif }
void Thread::SetPriority(int priority) { #ifdef URHO3D_THREADING #ifdef _WIN32 if (handle_) SetThreadPriority((HANDLE)handle_, priority); #elif defined(__linux__) && !defined(__ANDROID__) && !defined(__EMSCRIPTEN__) pthread_t* thread = (pthread_t*)handle_; if (thread) pthread_setschedprio(*thread, priority); #endif #endif // URHO3D_THREADING }
void *a_thread_func() { struct sched_param sparam; int policy, priority, policy_1; int rc; policy = SCHED_FIFO; priority = sched_get_priority_min(policy); sparam.sched_priority = priority; rc = pthread_setschedparam(pthread_self(), policy, &sparam); if (rc != 0) { printf("Error at pthread_setschedparam: rc=%d\n", rc); exit(PTS_UNRESOLVED); } rc = pthread_getschedparam(pthread_self(), &policy_1, &sparam); if (rc != 0) { printf("Error at pthread_getschedparam: rc=%d\n", rc); exit(PTS_UNRESOLVED); } printf("policy: %d, priority: %d\n", policy_1, sparam.sched_priority); if (policy_1 != policy || sparam.sched_priority != priority) { printf("pthread_getschedparam did not get the correct value\n"); exit(PTS_UNRESOLVED); } rc = pthread_setschedprio(pthread_self(), priority + 1); if (rc != 0) { printf("Error at pthread_setschedprio: rc=%d\n", rc); exit(PTS_FAIL); } rc = pthread_getschedparam(pthread_self(), &policy_1, &sparam); if (rc != 0) { printf("Error at pthread_getschedparam: rc=%d\n", rc); exit(PTS_UNRESOLVED); } printf("policy: %d, priority: %d\n", policy_1, sparam.sched_priority); if (sparam.sched_priority != (priority + 1)) { printf("Priority is not set correctly\n"); exit(PTS_FAIL); } pthread_exit(0); return NULL; }
void* fetchworkercmh(void* arg) { pthread_attr_t thAttr; int policy = 0; pthread_attr_init(&thAttr); pthread_attr_getschedpolicy(&thAttr, &policy); pthread_setschedprio(pthread_self(), sched_get_priority_min(policy)); FetchWorker* fw = (FetchWorker*)arg; while(!fw->exit) { FetchQueue* mfsitem = NULL; PX_LOCK(&fw->mt); while(fw->head == NULL) { pthread_cond_wait(&fw->cv, &fw->mt); if(fw->exit) { PX_UNLOCK(&fw->mt); break; } } mfsitem = fw->head; if (mfsitem != NULL) { fw->head = fw->head->next; PX_UNLOCK(&fw->mt); /*---------process write back queue---------*/ ReadCMHToCache(mfsitem->cmh, mfsitem->filesize); free(mfsitem); } else { fw->tail = NULL; PX_UNLOCK(&fw->mt); } continue; } pthread_exit(NULL); }
OSAL_PUBLIC OSAL_STATUS osalThreadPrioritySet (OsalThread *thread, UINT32 priority) { #ifdef __linux__ INT32 status; struct sched_param param1; int policy1; int minPrio, maxPrio; OSAL_LOCAL_ENSURE(thread, "osalThreadPrioritySet(): Null thread pointer", OSAL_FAIL); if(pthread_getschedparam(*thread, &policy1, ¶m1) != 0){ osalLog (OSAL_LOG_LVL_ERROR, OSAL_LOG_DEV_STDOUT, "osalThreadPrioritySet(): could not get sched param !!!\n", 0, 0, 0, 0, 0, 0, 0, 0); return OSAL_FAIL; } minPrio = sched_get_priority_min(policy1); maxPrio = sched_get_priority_max(policy1); if ((priority < minPrio) || (priority > maxPrio)) { osalLog (OSAL_LOG_LVL_ERROR, OSAL_LOG_DEV_STDOUT, "osalThreadPrioritySet(): Erroneous priority !!!\n", 0, 0, 0, 0, 0, 0, 0, 0); return OSAL_FAIL; } status = pthread_setschedprio(*thread, priority); if(status) { osalLog (OSAL_LOG_LVL_ERROR, OSAL_LOG_DEV_STDOUT, "\nosalThreadPrioritySet(): set prio failed \n !", 0, 0, 0, 0, 0, 0, 0, 0); return OSAL_FAIL; } #else osalLog (OSAL_LOG_LVL_ERROR, OSAL_LOG_DEV_STDOUT, "\nosalThreadPrioritySet(): not implemented on this OS \n !", 0, 0, 0, 0, 0, 0, 0, 0); #endif return OSAL_SUCCESS; }
intptr_t thread_start_low_priority (void (*fn)(void *ctx), void *ctx) { #if defined(__linux__) && !defined(ANDROID) pthread_t tid; pthread_attr_t attr; int s = pthread_attr_init (&attr); if (s != 0) { fprintf (stderr, "pthread_attr_init failed: %s\n", strerror (s)); return 0; } #if !STATICLINK && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 4 int policy; s = pthread_attr_getschedpolicy (&attr, &policy); if (s != 0) { fprintf (stderr, "pthread_attr_getschedpolicy failed: %s\n", strerror (s)); return 0; } int minprio = sched_get_priority_min (policy); #endif s = pthread_create (&tid, &attr, (void *(*)(void *))fn, (void*)ctx); if (s != 0) { fprintf (stderr, "pthread_create failed: %s\n", strerror (s)); return 0; } #if !STATICLINK && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 4 s = pthread_setschedprio (tid, minprio); if (s != 0) { fprintf (stderr, "pthread_setschedprio failed: %s\n", strerror (s)); pthread_cancel (tid); return 0; } #endif s = pthread_attr_destroy (&attr); if (s != 0) { fprintf (stderr, "pthread_attr_destroy failed: %s\n", strerror (s)); pthread_cancel (tid); return 0; } return tid; #else return thread_start (fn, ctx); #endif }
static void tc_pthread_pthread_setschedprio(void) { int ret_chk; pthread_t set_th; uint8_t set_prio = 101; ret_chk = pthread_create(&set_th, NULL, setschedprio_test_thread, NULL); TC_ASSERT_EQ("pthread_create", ret_chk, OK); /* change set_th PID's priority to set_prio */ ret_chk = pthread_setschedprio(set_th, set_prio); TC_ASSERT_EQ("pthread_setschedprio", ret_chk, OK); ret_chk = pthread_join(set_th, NULL); TC_ASSERT_EQ("pthread_join", ret_chk, OK); TC_ASSERT_EQ("pthread_setschedprio", check_prio, set_prio); TC_SUCCESS_RESULT(); }
/* The main test function. */ int main( int argc, char *argv[] ) { int ret = 0; pthread_t child; pthread_attr_t ta; pthread_barrier_t bar; struct sched_param sp; /* Initialize output routine */ output_init(); ret = pthread_barrier_init( &bar, NULL, 2 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to init barrier" ); } /* Create the attribute object with a known scheduling policy */ ret = pthread_attr_init( &ta ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to initialize thread attribute" ); } ret = pthread_attr_setinheritsched( &ta, PTHREAD_EXPLICIT_SCHED ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to set inherit sched" ); } sp.sched_priority = sched_get_priority_min( SCHED_RR ); if ( sp.sched_priority == -1 ) { UNRESOLVED( errno, "Failed to get min priority" ); } ret = pthread_attr_setschedparam( &ta, &sp ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to set attribute param" ); } ret = pthread_attr_setschedpolicy( &ta, SCHED_RR ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to set attribute policy" ); } /* Create the thread with this attribute */ ret = pthread_create( &child, &ta, threaded, &bar ); if ( ret != 0 ) { UNRESOLVED( ret, "thread creation failed (you may need more priviledges)" ); } /* Wait while the thread checks its policy (we only check what is reported, not the real behavior) */ check_param( child, SCHED_RR, sched_get_priority_min( SCHED_RR ) ); ret = pthread_barrier_wait( &bar ); if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) ) { UNRESOLVED( ret, "barrier wait failed" ); } /* Change the threads policy */ sp.sched_priority = sched_get_priority_min( SCHED_FIFO ); if ( sp.sched_priority == -1 ) { UNRESOLVED( errno, "Failed to get min priority" ); } ret = pthread_setschedparam( child, SCHED_FIFO, &sp ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to change running thread's policy" ); } ret = pthread_barrier_wait( &bar ); if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) ) { UNRESOLVED( ret, "barrier wait failed" ); } /* Wait while the thread checks its policy (we only check what is reported, not the real behavior) */ check_param( child, SCHED_FIFO, sched_get_priority_min( SCHED_FIFO ) ); ret = pthread_barrier_wait( &bar ); if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) ) { UNRESOLVED( ret, "barrier wait failed" ); } /* Change the thread priority */ sp.sched_priority = sched_get_priority_max( SCHED_FIFO ); if ( sp.sched_priority == -1 ) { UNRESOLVED( errno, "Failed to get max priority" ); } ret = pthread_setschedprio( child, sp.sched_priority ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to raise thread's priority" ); } ret = pthread_barrier_wait( &bar ); if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) ) { UNRESOLVED( ret, "barrier wait failed" ); } /* The thread checks its priority (we only check what is reported, not the real behavior) */ check_param( child, SCHED_FIFO, sched_get_priority_max( SCHED_FIFO ) ); ret = pthread_barrier_wait( &bar ); if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) ) { UNRESOLVED( ret, "barrier wait failed" ); } ret = pthread_join( child, NULL ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to join the thread" ); } PASSED; }
static void* fetchworker(void* arg) { pthread_attr_t thAttr; int policy = 0; pthread_attr_init(&thAttr); pthread_attr_getschedpolicy(&thAttr, &policy); pthread_setschedprio(pthread_self(), sched_get_priority_min(policy)); PX_ASSERT(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)==0); FetchWorker* fw = (FetchWorker*)arg; // PathEntry* pe = NULL; while(!fw->exit) { FetchQueue* mfsitem; PX_LOCK(&fw->mt); while(fw->head == NULL) { pthread_cond_wait(&fw->cv, &fw->mt); if(fw->exit) { PX_UNLOCK(&fw->mt); break; } } mfsitem = fw->head; if (mfsitem != NULL) { fw->head = fw->head->next; PX_UNLOCK(&fw->mt); /*---------process write back queue---------*/ ReadFileToCache(mfsitem->rscpath, mfsitem->filesize); // *(mfsitem->flag) = '1' ; free(mfsitem); } else { fw->tail = NULL; PX_UNLOCK(&fw->mt); } continue; #ifdef USEFETCHCONF pe = readfetchconf(); while (pe != NULL) { if (pe->pt == PATHDIR_T) { fetchDir(pe->path); } else if (pe->pt == PATHFILE_T) { ReadFileToCache(pe->path); } PathEntry* freepe = pe; pe = pe->next; free(freepe); } printf("done fetchworker!\n"); sleep(FETCHWORKERSLEEPTIME); #endif } pthread_exit(NULL); }
void pluto_crypto_helper(int fd, int helpernum) { #ifdef HAVE_LIBNSS FILE *in = fdopen(fd, "rb"); FILE *out = fdopen(fd, "wb"); long reqbuf[PCR_REQ_SIZE/sizeof(long)]; struct pluto_crypto_req *r; /* OS X does not have pthread_setschedprio */ #if !(defined(macintosh) || (defined(__MACH__) && defined(__APPLE__))) int status=pthread_setschedprio(pthread_self(), 10); DBG(DBG_CONTROL, DBG_log("status value returned by setting the priority of this thread (id=%d) %d",helpernum,status)); #endif DBG(DBG_CONTROL, DBG_log("helper %d waiting on fd: %d" , helpernum, fileno(in))); memset(reqbuf, 0, sizeof(reqbuf)); while(fread((char*)reqbuf, sizeof(r->pcr_len), 1, in) == 1) { int restlen; int actnum; unsigned char *reqrest = ((unsigned char *)reqbuf)+sizeof(r->pcr_len); r = (struct pluto_crypto_req *)reqbuf; restlen = r->pcr_len-sizeof(r->pcr_len); passert(restlen < (signed)PCR_REQ_SIZE); passert(restlen > 0); actnum = fread(reqrest, 1, restlen, in); /* okay, got a basic size, read the rest of it */ DBG(DBG_CONTROL, DBG_log("helper %d read %d+4/%d bytes fd: %d" , helpernum, actnum, (int)r->pcr_len, fileno(in))); if(actnum != restlen) { /* faulty read. die, parent will restart us */ loglog(RC_LOG_SERIOUS, "cryptographic helper(%d) fread(%d)=%d failed: %s\n", (int)pthread_self(), restlen, actnum, strerror(errno)); loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: helper (%d) is error exiting\n",helpernum); goto error; } pluto_do_crypto_op(r,helpernum); actnum = fwrite((unsigned char *)r, r->pcr_len, 1, out); fflush(out); if(actnum != 1) { loglog(RC_LOG_SERIOUS, "failed to write answer: %d", actnum); goto error; } memset(reqbuf, 0, sizeof(reqbuf)); } if(!feof(in)) { loglog(RC_LOG_SERIOUS, "helper %d got error: %s", helpernum, strerror(ferror(in))); goto error; } /* probably normal EOF */ loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: helper (%d) is normal exiting\n",helpernum); error: fclose(in); fclose(out); /*pthread_exit();*/ #else FILE *in = fdopen(fd, "rb"); FILE *out = fdopen(fd, "wb"); struct pluto_crypto_req reqbuf[2]; struct pluto_crypto_req *r; signal(SIGHUP, catchhup); signal(SIGUSR1, catchusr1); pc_worker_num = helpernum; /* make us lower priority that average */ setpriority(PRIO_PROCESS, 0, 10); DBG(DBG_CONTROL, DBG_log("helper %d waiting on fd: %d" , helpernum, fileno(in))); memset(reqbuf, 0, sizeof(reqbuf)); while(fread((char*)reqbuf, sizeof(r->pcr_len), 1, in) == 1) { int restlen; int actnum; unsigned char *reqrest = ((unsigned char *)reqbuf)+sizeof(r->pcr_len); r = &reqbuf[0]; restlen = r->pcr_len-sizeof(r->pcr_len); passert(restlen < (signed)PCR_REQ_SIZE); passert(restlen > 0); actnum = fread(reqrest, 1, restlen, in); /* okay, got a basic size, read the rest of it */ DBG(DBG_CONTROL, DBG_log("helper %d read %d+4/%d bytesfd: %d" , helpernum, actnum, (int)r->pcr_len, fileno(in))); if(actnum != restlen) { /* faulty read. die, parent will restart us */ loglog(RC_LOG_SERIOUS, "cryptographic helper(%d) fread(%d)=%d failed: %s\n", getpid(), restlen, actnum, strerror(errno)); #ifdef DEBUG if(getenv("PLUTO_CRYPTO_HELPER_COREDUMP")) { if(fork()==0) { /* in child */ passert(actnum == 1); } } #endif loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: helper (%d) is error exiting\n",helpernum); exit(1); } pluto_do_crypto_op(r); actnum = fwrite((unsigned char *)r, r->pcr_len, 1, out); fflush(out); if(actnum != 1) { loglog(RC_LOG_SERIOUS, "failed to write answer: %d", actnum); exit(2); } memset(reqbuf, 0, sizeof(reqbuf)); } if(!feof(in)) { loglog(RC_LOG_SERIOUS, "helper %d got error: %s", helpernum, strerror(ferror(in))); } /* probably normal EOF */ fclose(in); fclose(out); loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: helper (%d) is normal exiting\n",helpernum); exit(0); #endif }
/** Start a clone task running under a pthread. * * @internal * * Allocates and initializes a sub-task with its own pthread. The sub-task is * represented by clone handle to the rest of the application. The function * su_clone_start() returns the clone handle in @a return_clone. The clone * handle is used to communicate with the newly created clone task using * messages. * * A new #su_root_t object is created for the sub-task with the @a magic as * the root context pointer. Because the sub-task may or may not have its * own thread, all its activity must be scheduled via this root object. In * other words, the sub-task can be schedule * -# I/O events with su_root_register() * -# timers with su_timer_set(), su_timer_set_at() or su_timer_run() * -# messages with su_msg_send(). * * Messages can also be used to pass information between tasks or threads. * * After the new thread has been launched, the initialization routine is * executed by the newly created thread. The calling thread blocks until * the initialization routine completes. If the initialization routine * returns #su_success (0), the sub-task is considered to be created * successfully. After the successful initialization, the sub-task continues * to execeute the function su_root_run(). * * If the initalization function @a init fails, the sub-task (either the * newly created thread or the current thread executing the su_clone_start() * function) calls the deinitialization function, and su_clone_start() * returns NULL. * * @param parent root to be cloned (may be NULL if multi-threaded) * @param return_clone reference to a clone [OUT] * @param magic pointer to user data * @param init initialization function * @param deinit deinitialization function * * @return 0 if successfull, -1 upon an error. * * @sa su_root_threading(), su_clone_task(), su_clone_stop(), su_clone_wait(), * su_clone_forget(). * */ int su_pthreaded_port_start(su_port_create_f *create, su_root_t *parent, su_clone_r return_clone, su_root_magic_t *magic, su_root_init_f init, su_root_deinit_f deinit) { struct clone_args arg = { /* create: */ NULL, /* parent: */ NULL, /* magic: */ NULL, /* init: */ NULL, /* deinit: */ NULL, /* mutex: */ { PTHREAD_MUTEX_INITIALIZER }, #if HAVE_OPEN_C /* cv: */ { _ENeedsNormalInit, NULL }, #else /* cv: */ { PTHREAD_COND_INITIALIZER }, #endif /* retval: */ -1, /* clone: */ SU_MSG_R_INIT, }; int thread_created = 0; pthread_t tid; pthread_attr_t attr; struct sched_param param; arg.create = create; arg.parent = parent; arg.magic = magic; arg.init = init; arg.deinit = deinit; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 244); pthread_attr_getschedparam(&attr, ¶m); param.sched_priority = 99; pthread_attr_setschedparam(&attr, ¶m); pthread_mutex_lock(arg.mutex); if (pthread_create(&tid, &attr, su_pthread_port_clone_main, &arg) == 0) { #ifdef HAVE_PTHREAD_SETSCHEDPRIO pthread_setschedprio(tid, 99); #endif pthread_cond_wait(arg.cv, arg.mutex); thread_created = 1; } pthread_attr_destroy(&attr); pthread_mutex_unlock(arg.mutex); pthread_mutex_destroy(arg.mutex); pthread_cond_destroy(arg.cv); if (arg.retval != 0) { if (thread_created) pthread_join(tid, NULL); return -1; } *return_clone = *arg.clone; return 0; }
/* IN A HELPER THREAD */ static void pluto_crypto_helper(int helper_fd, int helpernum) { FILE *in = fdopen(helper_fd, "rb"); FILE *out = fdopen(helper_fd, "wb"); struct pluto_crypto_req req; /* OS X does not have pthread_setschedprio */ #if USE_PTHREAD_SETSCHEDPRIO int status = pthread_setschedprio(pthread_self(), 10); DBG(DBG_CONTROL, DBG_log("status value returned by setting the priority of this thread (crypto helper %d) %d", helpernum, status)); #endif DBG(DBG_CONTROL, DBG_log("crypto helper %d waiting on fd %d", helpernum, fileno(in))); passert(offsetof(struct pluto_crypto_req, pcr_len) == 0); for (;;) { size_t sz; errno = 0; sz = fread(&req, sizeof(char), sizeof(req), in); if (sz == 0 && feof(in)) { loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: crypto helper %d normal exit (EOF)", helpernum); break; } else if (sz != sizeof(req)) { if (ferror(in) != 0) { /* ??? is strerror(ferror(in)) correct? */ char errbuf[100]; /* ??? how big is big enough? */ strerror_r(errno, errbuf, sizeof(errbuf)); loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: crypto helper %d got read error: %s", helpernum, errbuf); } else { /* short read -- fatal */ loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: crypto helper %d got a short read error: %zu instead of %zu", helpernum, sz, sizeof(req)); } break; } passert(req.pcr_len == sizeof(req)); DBG(DBG_CONTROL, DBG_log("crypto helper %d read fd: %d", helpernum, fileno(in))); pluto_do_crypto_op(&req, helpernum); passert(req.pcr_len == sizeof(req)); errno = 0; sz = fwrite(&req, sizeof(char), sizeof(req), out); fflush(out); if (sz != sizeof(req)) { if (ferror(out) != 0) { /* ??? is strerror(ferror(out)) correct? */ char errbuf[100]; /* ??? how big is big enough? */ strerror_r(errno, errbuf, sizeof(errbuf)); loglog(RC_LOG_SERIOUS, "crypto helper %d failed to write answer: %s", helpernum, errbuf); } else { /* short write -- fatal */ loglog(RC_LOG_SERIOUS, "pluto_crypto_helper error: crypto helper %d write truncated: %zu instead of %zu", helpernum, sz, sizeof(req)); } break; } } /* We have no way to report this thread's success or failure. */ fclose(in); fclose(out); /*pthread_exit();*/ }
int main(){ /* Set all activation to 2 seconds after the current time*/ struct timespec dt; dt.tv_sec = 2; dt.tv_nsec = 0; clock_gettime(CLOCK_MONOTONIC, &activation_time[0]); for(int i = 1; i < 3; i++){ activation_time[i] = activation_time[0]; activation_time[i].tv_sec += dt.tv_sec; } activation_time[0].tv_sec += dt.tv_sec; // Lock the memory mlockall(MCL_CURRENT|MCL_FUTURE); /* For each thread change the scheduler to FIFO and set the priorities (right now in RMPO) */ pthread_attr_t attr[3]; pthread_attr_init(&attr[0]); pthread_attr_setschedpolicy(&attr[0], SCHED_FIFO); struct sched_param priority[3]; priority[0].sched_priority = sched_get_priority_max(SCHED_FIFO); pthread_attr_setschedparam(&attr[0],&priority[0]); pthread_attr_setinheritsched(&attr[0], PTHREAD_EXPLICIT_SCHED); pthread_attr_init(&attr[1]); pthread_attr_setschedpolicy(&attr[1], SCHED_FIFO); priority[1].sched_priority = sched_get_priority_max(SCHED_FIFO)-1; pthread_attr_setschedparam(&attr[1],&priority[1]); pthread_attr_setinheritsched(&attr[1], PTHREAD_EXPLICIT_SCHED); pthread_attr_init(&attr[2]); pthread_attr_setschedpolicy(&attr[2], SCHED_FIFO); priority[2].sched_priority = sched_get_priority_max(SCHED_FIFO)-2; pthread_attr_setschedparam(&attr[2],&priority[2]); pthread_attr_setinheritsched(&attr[2], PTHREAD_EXPLICIT_SCHED); /* Set threads affinity to CPU 0 */ cpu_set_t my_set; CPU_ZERO(&my_set); CPU_SET(0, &my_set); pthread_attr_setaffinity_np(&attr[0], sizeof(my_set), &my_set); pthread_attr_setaffinity_np(&attr[1], sizeof(my_set), &my_set); pthread_attr_setaffinity_np(&attr[2], sizeof(my_set), &my_set); /* Set the main thread to lowest priority */ //important!! without this the response times changed between switches! pthread_t self = pthread_self(); //pthread_setaffinity_np(self, sizeof(my_set), &my_set); pthread_setschedprio(self, sched_get_priority_min(SCHED_FIFO)); /* Create all the threads */ printf("======Starting in RMPO======\n"); if(pthread_create(&(thr[0]), &attr[0], function1, NULL) < 0){ printf("Error %s\n",strerror(errno)); exit(0); } if(pthread_create(&(thr[1]), &attr[1], function2, NULL) < 0){ printf("Error %s\n",strerror(errno)); exit(0); } if(pthread_create(&(thr[2]), &attr[2], function3, NULL) < 0){ printf("Error %s\n",strerror(errno)); exit(0); } /* Configure the periods and start times for the tasks using rtai like functions */ struct timespec _dt; _dt.tv_sec = 0; _dt.tv_nsec = (PERIOD1_MS)* 1000000; rt_task_make_periodic(&thr[0], activation_time[0], _dt); _dt.tv_sec = 0; _dt.tv_nsec = (PERIOD2_MS)* 1000000; rt_task_make_periodic(&thr[1], activation_time[1], _dt); _dt.tv_sec = 0; _dt.tv_nsec = (PERIOD3_MS)* 1000000; rt_task_make_periodic(&thr[2], activation_time[2], _dt); /* This will sleep for 5 seconds, then cancel all threads and print the worst response times. */ while(1){ sleep(5); pthread_cancel(thr[0]); pthread_cancel(thr[1]); pthread_cancel(thr[2]); printf("1 - worse response time: %lds and %ldms\n", worse_response_time[0].tv_sec, worse_response_time[0].tv_nsec/1000000); worse_response_time[0].tv_sec = 0; worse_response_time[0].tv_nsec = 0; printf("2 - worse response time: %lds and %ldms\n", worse_response_time[1].tv_sec, worse_response_time[1].tv_nsec/1000000); worse_response_time[1].tv_sec = 0; worse_response_time[1].tv_nsec = 0; printf("3 - worse response time: %lds and %ldms\n", worse_response_time[2].tv_sec, worse_response_time[2].tv_nsec/1000000); worse_response_time[2].tv_sec = 0; worse_response_time[2].tv_nsec = 0; exit(0); //pause(); } }
int hook_enable() { // Lock the thread control mutex. This will be unlocked when the // thread has finished starting, or when it has fully stopped. #ifdef _WIN32 WaitForSingleObject(hook_control_mutex, INFINITE); #else pthread_mutex_lock(&hook_control_mutex); #endif // Set the initial status. int status = UIOHOOK_FAILURE; #ifndef _WIN32 // Create the thread attribute. pthread_attr_t hook_thread_attr; pthread_attr_init(&hook_thread_attr); // Get the policy and priority for the thread attr. int policy; pthread_attr_getschedpolicy(&hook_thread_attr, &policy); int priority = sched_get_priority_max(policy); #endif #if defined(_WIN32) DWORD hook_thread_id; DWORD *hook_thread_status = malloc(sizeof(DWORD)); hook_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) hook_thread_proc, hook_thread_status, 0, &hook_thread_id); if (hook_thread != INVALID_HANDLE_VALUE) { #else int *hook_thread_status = malloc(sizeof(int)); if (pthread_create(&hook_thread, &hook_thread_attr, hook_thread_proc, hook_thread_status) == 0) { #endif #if defined(_WIN32) // Attempt to set the thread priority to time critical. if (SetThreadPriority(hook_thread, THREAD_PRIORITY_TIME_CRITICAL) == 0) { logger_proc(LOG_LEVEL_WARN, "%s [%u]: Could not set thread priority %li for thread %#p! (%#lX)\n", __FUNCTION__, __LINE__, (long) THREAD_PRIORITY_TIME_CRITICAL, hook_thread , (unsigned long) GetLastError()); } #elif (defined(__APPLE__) && defined(__MACH__)) || _POSIX_C_SOURCE >= 200112L // Some POSIX revisions do not support pthread_setschedprio so we will // use pthread_setschedparam instead. struct sched_param param = { .sched_priority = priority }; if (pthread_setschedparam(hook_thread, SCHED_OTHER, ¶m) != 0) { logger_proc(LOG_LEVEL_WARN, "%s [%u]: Could not set thread priority %i for thread 0x%lX!\n", __FUNCTION__, __LINE__, priority, (unsigned long) hook_thread); } #else // Raise the thread priority using glibc pthread_setschedprio. if (pthread_setschedprio(hook_thread, priority) != 0) { logger_proc(LOG_LEVEL_WARN, "%s [%u]: Could not set thread priority %i for thread 0x%lX!\n", __FUNCTION__, __LINE__, priority, (unsigned long) hook_thread); } #endif // Wait for the thread to indicate that it has passed the // initialization portion by blocking until either a EVENT_HOOK_ENABLED // event is received or the thread terminates. // NOTE This unlocks the hook_control_mutex while we wait. #ifdef _WIN32 WaitForSingleObject(hook_control_cond, INFINITE); #else pthread_cond_wait(&hook_control_cond, &hook_control_mutex); #endif #ifdef _WIN32 if (WaitForSingleObject(hook_running_mutex, 0) != WAIT_TIMEOUT) { #else if (pthread_mutex_trylock(&hook_running_mutex) == 0) { #endif // Lock Successful; The hook is not running but the hook_control_cond // was signaled! This indicates that there was a startup problem! // Get the status back from the thread. #ifdef _WIN32 WaitForSingleObject(hook_thread, INFINITE); GetExitCodeThread(hook_thread, hook_thread_status); #else pthread_join(hook_thread, (void **) &hook_thread_status); status = *hook_thread_status; #endif } else { // Lock Failure; The hook is currently running and wait was signaled // indicating that we have passed all possible start checks. We can // always assume a successful startup at this point. status = UIOHOOK_SUCCESS; } free(hook_thread_status); logger_proc(LOG_LEVEL_DEBUG, "%s [%u]: Thread Result: (%#X).\n", __FUNCTION__, __LINE__, status); } else { status = UIOHOOK_ERROR_THREAD_CREATE; } // Make sure the control mutex is unlocked. #ifdef _WIN32 ReleaseMutex(hook_control_mutex); #else pthread_mutex_unlock(&hook_control_mutex); #endif return status; } int main() { // Lock the thread control mutex. This will be unlocked when the // thread has finished starting, or when it has fully stopped. #ifdef _WIN32 // Create event handles for the thread hook. hook_running_mutex = CreateMutex(NULL, FALSE, TEXT("hook_running_mutex")); hook_control_mutex = CreateMutex(NULL, FALSE, TEXT("hook_control_mutex")); hook_control_cond = CreateEvent(NULL, TRUE, FALSE, TEXT("hook_control_cond")); #else pthread_mutex_init(&hook_running_mutex, NULL); pthread_mutex_init(&hook_control_mutex, NULL); pthread_cond_init(&hook_control_cond, NULL); #endif // Set the logger callback for library output. hook_set_logger_proc(&logger_proc); // Set the event callback for uiohook events. hook_set_dispatch_proc(&dispatch_proc); // Start the hook and block. // NOTE If EVENT_HOOK_ENABLED was delivered, the status will always succeed. int status = hook_enable(); switch (status) { case UIOHOOK_SUCCESS: // We no longer block, so we need to explicitly wait for the thread to die. #ifdef _WIN32 WaitForSingleObject(hook_thread, INFINITE); #else #if defined(__APPLE__) && defined(__MACH__) // NOTE Darwin requires that you start your own runloop from main. CFRunLoopRun(); #endif pthread_join(hook_thread, NULL); #endif break; // System level errors. case UIOHOOK_ERROR_OUT_OF_MEMORY: logger_proc(LOG_LEVEL_ERROR, "Failed to allocate memory. (%#X)\n", status); break; // X11 specific errors. case UIOHOOK_ERROR_X_OPEN_DISPLAY: logger_proc(LOG_LEVEL_ERROR, "Failed to open X11 display. (%#X)\n", status); break; case UIOHOOK_ERROR_X_RECORD_NOT_FOUND: logger_proc(LOG_LEVEL_ERROR, "Unable to locate XRecord extension. (%#X)\n", status); break; case UIOHOOK_ERROR_X_RECORD_ALLOC_RANGE: logger_proc(LOG_LEVEL_ERROR, "Unable to allocate XRecord range. (%#X)\n", status); break; case UIOHOOK_ERROR_X_RECORD_CREATE_CONTEXT: logger_proc(LOG_LEVEL_ERROR, "Unable to allocate XRecord context. (%#X)\n", status); break; case UIOHOOK_ERROR_X_RECORD_ENABLE_CONTEXT: logger_proc(LOG_LEVEL_ERROR, "Failed to enable XRecord context. (%#X)\n", status); break; // Windows specific errors. case UIOHOOK_ERROR_SET_WINDOWS_HOOK_EX: logger_proc(LOG_LEVEL_ERROR, "Failed to register low level windows hook. (%#X)\n", status); break; // Darwin specific errors. case UIOHOOK_ERROR_AXAPI_DISABLED: logger_proc(LOG_LEVEL_ERROR, "Failed to enable access for assistive devices. (%#X)\n", status); break; case UIOHOOK_ERROR_CREATE_EVENT_PORT: logger_proc(LOG_LEVEL_ERROR, "Failed to create apple event port. (%#X)\n", status); break; case UIOHOOK_ERROR_CREATE_RUN_LOOP_SOURCE: logger_proc(LOG_LEVEL_ERROR, "Failed to create apple run loop source. (%#X)\n", status); break; case UIOHOOK_ERROR_GET_RUNLOOP: logger_proc(LOG_LEVEL_ERROR, "Failed to acquire apple run loop. (%#X)\n", status); break; case UIOHOOK_ERROR_CREATE_OBSERVER: logger_proc(LOG_LEVEL_ERROR, "Failed to create apple run loop observer. (%#X)\n", status); break; // Default error. case UIOHOOK_FAILURE: default: logger_proc(LOG_LEVEL_ERROR, "An unknown hook error occurred. (%#X)\n", status); break; } #ifdef _WIN32 // Create event handles for the thread hook. CloseHandle(hook_thread); CloseHandle(hook_running_mutex); CloseHandle(hook_control_mutex); CloseHandle(hook_control_cond); #else pthread_mutex_destroy(&hook_running_mutex); pthread_mutex_destroy(&hook_control_mutex); pthread_cond_destroy(&hook_control_cond); #endif return status; }
void osc_start_updater_thread() { pthread_create( &thread_osc_updater, NULL, osc_start_updater, (void*) NULL); pthread_setschedprio(thread_osc_updater, 80); }
void pluto_crypto_helper(int fd, int helpernum) { FILE *in = fdopen(fd, "rb"); FILE *out = fdopen(fd, "wb"); long reqbuf[PCR_REQ_SIZE/sizeof(long)]; struct pluto_crypto_req *r; /* OS X does not have pthread_setschedprio */ #if !(defined(macintosh) || (defined(__MACH__) && defined(__APPLE__))) int status=pthread_setschedprio(pthread_self(), 10); DBG(DBG_CONTROL, DBG_log("status value returned by setting the priority of this thread (id=%d) %d",helpernum,status)); #endif DBG(DBG_CONTROL, DBG_log("helper %d waiting on fd: %d" , helpernum, fileno(in))); memset(reqbuf, 0, sizeof(reqbuf)); while(fread((char*)reqbuf, sizeof(r->pcr_len), 1, in) == 1) { int restlen; int actnum; unsigned char *reqrest = ((unsigned char *)reqbuf)+sizeof(r->pcr_len); r = (struct pluto_crypto_req *)reqbuf; restlen = r->pcr_len-sizeof(r->pcr_len); passert(restlen < (signed)PCR_REQ_SIZE); passert(restlen > 0); actnum = fread(reqrest, 1, restlen, in); /* okay, got a basic size, read the rest of it */ DBG(DBG_CONTROL, DBG_log("helper %d read %d+4/%d bytes fd: %d" , helpernum, actnum, (int)r->pcr_len, fileno(in))); if(actnum != restlen) { /* faulty read. die, parent will restart us */ loglog(RC_LOG_SERIOUS, "cryptographic helper(%d) fread(%d)=%d failed: %s\n", (int)pthread_self(), restlen, actnum, strerror(errno)); loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: helper (%d) is error exiting\n",helpernum); goto error; } pluto_do_crypto_op(r,helpernum); actnum = fwrite((unsigned char *)r, r->pcr_len, 1, out); fflush(out); if(actnum != 1) { loglog(RC_LOG_SERIOUS, "failed to write answer: %d", actnum); goto error; } memset(reqbuf, 0, sizeof(reqbuf)); } if(!feof(in)) { loglog(RC_LOG_SERIOUS, "helper %d got error: %s", helpernum, strerror(ferror(in))); goto error; } /* probably normal EOF */ loglog(RC_LOG_SERIOUS, "pluto_crypto_helper: helper (%d) is exiting (eof, normal)\n",helpernum); error: fclose(in); fclose(out); /*pthread_exit();*/ }
#endif static int wrap_pthread_sigmask(int how, const sigset_t *restrict set, sigset_t *restrict oset) { WRAP_START while (!err) err = pthread_sigmask(how, set, oset); WRAP_END } #ifndef MUSL static int wrap_pthread_setschedprio(pthread_t thread, int prio) { WRAP_START while (!err) err = pthread_setschedprio(thread, prio); WRAP_END } #endif static int wrap_pthread_setconcurrency(int new_level) { WRAP_START while (!err) err = pthread_setconcurrency(new_level); WRAP_END } static int wrap_pthread_detach(pthread_t thread) { WRAP_START while (!err) err = pthread_detach(thread);
//=======pThread Definition================================================== void *my_thread(void * arg){ char in_buf[BUF_SIZE]; // Input buffer for GET resquest char out_buf[BUF_SIZE]; // Output buffer for HTML response char *file_name; // File name unsigned int fh; // File handle (file descriptor) unsigned int buf_len; // Buffer length for file reads unsigned int retcode; // Return code int priority; // Used when testing for priority unsigned int myClient_s; myClient_s = *(unsigned int*) arg; //receive the first HTTP request (HTTP GET) retcode = recv(myClient_s, in_buf, BUF_SIZE, 0); //if receive error if (retcode < 0){ printf("recv error detected ...\n"); } else{ strtok(in_buf, " "); file_name = strtok(NULL, " "); //High priority===========================================================// if(strcmp(&file_name[1], "test_00.jpg") == 0){ priority = pthread_setschedprio(pthread_self(), IM_HIGH); if(priority){ printf("\n this is really HIGH...priority \n"); } else{ printf("\n Priority no work right \n"); } } //========================================================================// fh = open(&file_name[1], O_RDONLY, S_IREAD | S_IWRITE); if (fh == -1){ printf("File %s not found - sending an HTTP 404 \n", &file_name[1]); strcpy(out_buf, NOTOK_404); send(myClient_s, out_buf, strlen(out_buf), 0); strcpy(out_buf, MESS_404); send(myClient_s, out_buf, strlen(out_buf), 0); } else{ printf("File %s is being sent \n", &file_name[1]); if ((strstr(file_name, ".jpg") != NULL)||(strstr(file_name, ".gif") != NULL)) { strcpy(out_buf, OK_IMAGE); } else{ strcpy(out_buf, OK_TEXT); } send(myClient_s, out_buf, strlen(out_buf), 0); buf_len = 1; int count; count = 0; while (buf_len > 0){ buf_len = read(fh, out_buf, BUF_SIZE); if (buf_len > 0){ send(myClient_s, out_buf, buf_len, 0); count = count +1; if(count = 500){ printf("%d bytes transferred..\n",buf_len); count = 0; }//end count if }//end buf_len >0 }//end while() close(fh); // close the file close(myClient_s); // close the client connection pthread_exit(NULL); //closing the thread }// end fh == -1 if }// end recieve if return arg; }//end pThread