pthread_t uorb_receive_start(void) { /* --- SENSORS RAW VALUE --- */ mavlink_subs.sensor_sub = orb_subscribe(ORB_ID(sensor_combined)); /* rate limit set externally based on interface speed, set a basic default here */ orb_set_interval(mavlink_subs.sensor_sub, 200); /* 5Hz updates */ /* --- ATTITUDE VALUE --- */ mavlink_subs.att_sub = orb_subscribe(ORB_ID(vehicle_attitude)); /* rate limit set externally based on interface speed, set a basic default here */ orb_set_interval(mavlink_subs.att_sub, 200); /* 5Hz updates */ /* --- GPS VALUE --- */ mavlink_subs.gps_sub = orb_subscribe(ORB_ID(vehicle_gps_position)); orb_set_interval(mavlink_subs.gps_sub, 200); /* 5Hz updates */ /* --- HOME POSITION --- */ mavlink_subs.home_sub = orb_subscribe(ORB_ID(home_position)); orb_set_interval(mavlink_subs.home_sub, 1000); /* 1Hz updates */ /* --- SYSTEM STATE --- */ status_sub = orb_subscribe(ORB_ID(vehicle_status)); orb_set_interval(status_sub, 300); /* max 3.33 Hz updates */ /* --- RC CHANNELS VALUE --- */ rc_sub = orb_subscribe(ORB_ID(rc_channels)); orb_set_interval(rc_sub, 100); /* 10Hz updates */ /* --- RC RAW VALUE --- */ mavlink_subs.input_rc_sub = orb_subscribe(ORB_ID(input_rc)); orb_set_interval(mavlink_subs.input_rc_sub, 100); /* --- GLOBAL POS VALUE --- */ mavlink_subs.global_pos_sub = orb_subscribe(ORB_ID(vehicle_global_position)); orb_set_interval(mavlink_subs.global_pos_sub, 100); /* 10 Hz active updates */ /* --- LOCAL POS VALUE --- */ mavlink_subs.local_pos_sub = orb_subscribe(ORB_ID(vehicle_local_position)); orb_set_interval(mavlink_subs.local_pos_sub, 1000); /* 1Hz active updates */ /* --- GLOBAL SETPOINT VALUE --- */ mavlink_subs.spg_sub = orb_subscribe(ORB_ID(vehicle_global_position_setpoint)); orb_set_interval(mavlink_subs.spg_sub, 2000); /* 0.5 Hz updates */ /* --- LOCAL SETPOINT VALUE --- */ mavlink_subs.spl_sub = orb_subscribe(ORB_ID(vehicle_local_position_setpoint)); orb_set_interval(mavlink_subs.spl_sub, 2000); /* 0.5 Hz updates */ /* --- ATTITUDE SETPOINT VALUE --- */ mavlink_subs.spa_sub = orb_subscribe(ORB_ID(vehicle_attitude_setpoint)); orb_set_interval(mavlink_subs.spa_sub, 2000); /* 0.5 Hz updates */ /* --- RATES SETPOINT VALUE --- */ mavlink_subs.rates_setpoint_sub = orb_subscribe(ORB_ID(vehicle_rates_setpoint)); orb_set_interval(mavlink_subs.rates_setpoint_sub, 2000); /* 0.5 Hz updates */ /* --- ACTUATOR OUTPUTS --- */ mavlink_subs.act_0_sub = orb_subscribe(ORB_ID(actuator_outputs_0)); mavlink_subs.act_1_sub = orb_subscribe(ORB_ID(actuator_outputs_1)); mavlink_subs.act_2_sub = orb_subscribe(ORB_ID(actuator_outputs_2)); mavlink_subs.act_3_sub = orb_subscribe(ORB_ID(actuator_outputs_3)); /* rate limits set externally based on interface speed, set a basic default here */ orb_set_interval(mavlink_subs.act_0_sub, 100); /* 10Hz updates */ orb_set_interval(mavlink_subs.act_1_sub, 100); /* 10Hz updates */ orb_set_interval(mavlink_subs.act_2_sub, 100); /* 10Hz updates */ orb_set_interval(mavlink_subs.act_3_sub, 100); /* 10Hz updates */ /* --- ACTUATOR ARMED VALUE --- */ mavlink_subs.armed_sub = orb_subscribe(ORB_ID(actuator_armed)); orb_set_interval(mavlink_subs.armed_sub, 100); /* 10Hz updates */ /* --- MAPPED MANUAL CONTROL INPUTS --- */ mavlink_subs.man_control_sp_sub = orb_subscribe(ORB_ID(manual_control_setpoint)); /* rate limits set externally based on interface speed, set a basic default here */ orb_set_interval(mavlink_subs.man_control_sp_sub, 100); /* 10Hz updates */ /* --- ACTUATOR CONTROL VALUE --- */ mavlink_subs.actuators_effective_sub = orb_subscribe(ORB_ID_VEHICLE_ATTITUDE_CONTROLS_EFFECTIVE); orb_set_interval(mavlink_subs.actuators_effective_sub, 100); /* 10Hz updates */ mavlink_subs.actuators_sub = orb_subscribe(ORB_ID_VEHICLE_ATTITUDE_CONTROLS); orb_set_interval(mavlink_subs.actuators_sub, 100); /* 10Hz updates */ /* --- DEBUG VALUE OUTPUT --- */ mavlink_subs.debug_key_value = orb_subscribe(ORB_ID(debug_key_value)); orb_set_interval(mavlink_subs.debug_key_value, 100); /* 10Hz updates */ /* --- FLOW SENSOR --- */ mavlink_subs.optical_flow = orb_subscribe(ORB_ID(optical_flow)); orb_set_interval(mavlink_subs.optical_flow, 200); /* 5Hz updates */ /* --- AIRSPEED / VFR / HUD --- */ mavlink_subs.airspeed_sub = orb_subscribe(ORB_ID(airspeed)); orb_set_interval(mavlink_subs.airspeed_sub, 200); /* 5Hz updates */ /* start the listener loop */ pthread_attr_t uorb_attr; pthread_attr_init(&uorb_attr); /* Set stack size, needs less than 2k */ pthread_attr_setstacksize(&uorb_attr, 2048); pthread_t thread; pthread_create(&thread, &uorb_attr, uorb_receive_thread, NULL); return thread; }
static int conpar_threads_wrapper(integer nov, integer na, integer nra, integer nca, doublereal ***a, integer ncb, doublereal ***b, integer nrc, doublereal ***c, doublereal **d, integer *irf, integer *icf) { conpar_parallel_arglist *data; int i,j,k; pthread_t *th; void * retval; pthread_attr_t attr; int retcode; #ifdef USAGE struct timeval *pthreads_wait; time_start(&pthreads_wait); #endif data = (conpar_parallel_arglist *)malloc(sizeof(conpar_parallel_arglist)*global_num_procs); th = (pthread_t *)malloc(sizeof(pthread_t)*global_num_procs); for(i=0;i<global_num_procs;i++) { integer loop_start, loop_end; /*start and end of the computed loop*/ loop_start = (i*na)/global_num_procs; loop_end = ((i+1)*na)/global_num_procs; /*3D Arrays*/ data[i].a = a + loop_start; data[i].b = b + loop_start; data[i].c = c + loop_start; /*2D Arrays*/ data[i].irf = irf + loop_start*nra; data[i].icf = icf + loop_start*nca; /*Scalars*/ data[i].nrc = nrc; data[i].ncb = ncb; data[i].nov = nov; data[i].nra = nra; data[i].nca = nca; data[i].na = loop_end - loop_start; } pthread_attr_init(&attr); pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM); for(i=0;i<global_num_procs;i++) { retcode = pthread_create(&th[i], &attr, conpar_threads_process, (void *) &data[i]); if (retcode != 0) fprintf(stderr, "create %d failed %d\n", i, retcode); } for(i=0;i<global_num_procs;i++) { retcode = pthread_join(th[i], &retval); if (retcode != 0) fprintf(stderr, "join %d failed %d\n", i, retcode); /* This is were we sum into the global copy of the d array */ for(j=0;j<nrc;j++) for (k=0; k<ncb;k++) d[j][k] += data[i].d[j][k]; free_dmatrix(data[i].d); } free(data); free(th); #ifdef USAGE time_end(pthreads_wait,"conpar pthreads wrapper",fp9); #endif return 0; }
ThreadAttr(): thread_stack_size(262144) { pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, thread_stack_size); }
int main( int argc, char ** argv ) { // Print usage if not enough arguments signal(SIGCHLD,handel); signal(SIGPIPE,handel1); if ( argc < 2 ) { fprintf( stderr, "%s", usage ); exit( -1 ); } int port; // Get the port from the arguments int cases = 0; if(argc == 3){ port = atoi(argv[2]); if(strcmp(argv[1],"-f") == 0){ cases = 1; }else if(strcmp(argv[1],"-t") == 0){ cases = 2; }else{ cases = 3; } }else if(argc == 2){ if(isnumber(argv[1]) == 1){ port = atoi( argv[1] ); cases = 0; }else { if(strcmp(argv[1],"-f") == 0){ cases = 1; }else if(strcmp(argv[1],"-t") == 0){ cases = 2; }else if(strcmp(argv[1],"-p") == 0){ cases = 3; } port = 8000; } }else if(argc == 1){ cases = 0; port = 8000; } // Set the IP address and port for this server struct sockaddr_in serverIPAddress; memset( &serverIPAddress, 0, sizeof(serverIPAddress) ); serverIPAddress.sin_family = AF_INET; serverIPAddress.sin_addr.s_addr = INADDR_ANY; serverIPAddress.sin_port = htons((u_short) port); // Allocate a socket int masterSocket = socket(PF_INET, SOCK_STREAM, 0); if ( masterSocket < 0) { // perror("socket"); exit( -1 ); } // Set socket options to reuse port. Otherwise we will // have to wait about 2 minutes before reusing the sae port number int optval = 1; int err = setsockopt(masterSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof( int ) ); // Bind the socket to the IP address and port int error = bind( masterSocket, (struct sockaddr *)&serverIPAddress, sizeof(serverIPAddress) ); if ( error ) { // perror("bind"); exit( -1 ); } // Put socket in listening mode and set the // size of the queue of unprocessed connections error = listen( masterSocket, QueueLength); if ( error ) { // perror("listen"); exit( -1 ); } if(cases == 0){ while ( 1 ) { // Accept incoming connections struct sockaddr_in clientIPAddress; int alen = sizeof( clientIPAddress ); int slaveSocket = accept( masterSocket, (struct sockaddr *)&clientIPAddress, (socklen_t*)&alen); /* if ( slaveSocket < 0 ) { perror( "accept" ); exit( -1 ); }*/ // Process request. processTimeRequest( slaveSocket ); // Close socket close( slaveSocket ); } } else if(cases == 1){ printf("case 1\n"); while ( 1 ) { // Accept incoming connections struct sockaddr_in clientIPAddress; int alen = sizeof( clientIPAddress ); int slaveSocket = accept( masterSocket, (struct sockaddr *)&clientIPAddress, (socklen_t*)&alen); if ( slaveSocket < 0 ) { // perror( "accept" ); exit( -1 ); } pid_t f = fork(); if(f == 0){ // Process request. processTimeRequest( slaveSocket ); close( slaveSocket ); exit(EXIT_SUCCESS); } /* if(slaveSocket == -1 && errno == EINTR){ continue; }*/ close(slaveSocket); } } else if(cases == 2){ printf("case 2\n"); while ( 1 ) { // Accept incoming connections struct sockaddr_in clientIPAddress; int alen = sizeof( clientIPAddress ); int slaveSocket = accept( masterSocket, (struct sockaddr *)&clientIPAddress, (socklen_t*)&alen); if ( slaveSocket < 0 ) { // perror( "accept" ); exit( -1 ); }else{ pthread_t t1; pthread_attr_t attr; pthread_attr_init( &attr ); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // Process request. pthread_create(&t1, &attr, (void * (*) (void*)) processTimeRequest,(void *) slaveSocket); // processTimeRequest( slaveSocket ); // close( slaveSocket ); // pthread_join(t1,NULL); } } }else if(cases == 3){ printf("case3\n"); pthread_t tid[5]; pthread_attr_t attr; pthread_attr_init( &attr ); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); for (int i = 0; i < 5; i++) { pthread_create(&tid[i], &attr, (void * (*) (void*)) poolRequest,(void *) masterSocket); } pthread_join(tid[0],NULL); } }
void *clamukofsth(void *arg) { struct thrarg *tharg = (struct thrarg *) arg; sigset_t sigset; struct sigaction act; pthread_t *clamuko_pids = NULL; const char *groupname = "ClamAV"; int count; int started; /* is another server thread already working? */ if(pthread_mutex_trylock(&running_mutex)) return NULL; /* ignore all signals except SIGUSR1 */ sigfillset(&sigset); sigdelset(&sigset, SIGUSR1); /* The behavior of a process is undefined after it ignores a * SIGFPE, SIGILL, SIGSEGV, or SIGBUS signal */ sigdelset(&sigset, SIGFPE); sigdelset(&sigset, SIGILL); sigdelset(&sigset, SIGSEGV); #ifdef SIGBUS sigdelset(&sigset, SIGBUS); #endif pthread_sigmask(SIG_SETMASK, &sigset, NULL); count = optget(tharg->opts, "ClamukoScannerCount")->numarg; if(count < 1) goto out; clamuko_pids = calloc(count, sizeof(pthread_t)); if(!clamuko_pids) goto out; if(setup_shutdown_handle(groupname)) goto out; act.sa_handler = clamuko_exit; sigfillset(&(act.sa_mask)); sigaction(SIGUSR1, &act, NULL); sigaction(SIGSEGV, &act, NULL); for(started = 0; started < count; started++) { pthread_attr_t clamuko_attr; if(pthread_attr_init(&clamuko_attr)) break; pthread_attr_setdetachstate(&clamuko_attr, PTHREAD_CREATE_JOINABLE); if(pthread_create(&clamuko_pids[started], &clamuko_attr, clamuko_scanth, tharg)) break; logg("Clamuko: Started scanner thread %d.\n", started); } pthread_cond_wait(&shutdown_cond, &running_mutex); logg("Clamuko: Stop signal received.\n"); shutdown_clamuko(); for(started-- ; started >= 0; started--) { logg("Clamuko: Waiting for scanner thread %d to finish.\n", started); pthread_join(clamuko_pids[started], NULL); } logg("Clamuko: Stopped.\n"); out: if(clamuko_pids) free(clamuko_pids); pthread_mutex_unlock(&running_mutex); return NULL; }
void bu_parallel(void (*func)(int, void *), size_t ncpu, void *arg) { #ifndef PARALLEL if (!func) return; /* nothing to do */ bu_log("bu_parallel(%zu., %p): Not compiled for PARALLEL machine, running single-threaded\n", ncpu, arg); /* do the work anyways */ (*func)(0, arg); #else struct thread_data *thread_context; rt_thread_t thread_tbl[MAX_PSW]; size_t avail_cpus = 1; size_t x; size_t i; /* number of threads created/ended */ size_t nthreadc; size_t nthreade; char *libbu_affinity = NULL; /* OFF by default as modern schedulers are smarter than this. */ int affinity = 0; /* ncpu == 0 means throttle our thread creation as slots become available */ int throttle = 0; struct parallel_info *parent; rt_thread_t thread; if (!func) return; /* nothing to do */ if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(%zu, %p)\n", ncpu, arg); if (ncpu > MAX_PSW) { bu_log("WARNING: bu_parallel() ncpu(%zd) > MAX_PSW(%d), adjusting ncpu\n", ncpu, MAX_PSW); ncpu = MAX_PSW; } libbu_affinity = getenv("LIBBU_AFFINITY"); if (libbu_affinity) affinity = (int)strtol(libbu_affinity, NULL, 0x10); if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) { if (affinity) bu_log("CPU affinity enabled. (LIBBU_AFFINITY=%d)\n", affinity); else bu_log("CPU affinity disabled.\n"); } /* if we're in debug mode, allow additional cpus */ if (!(bu_debug & BU_DEBUG_PARALLEL)) { /* otherwise, limit ourselves to what is actually available */ avail_cpus = bu_avail_cpus(); if (ncpu > avail_cpus) { bu_log("%zd cpus requested, but only %d available\n", ncpu, avail_cpus); ncpu = avail_cpus; } } parent = parallel_mapping(PARALLEL_GET, bu_parallel_id(), ncpu); if (ncpu < 1) { /* want to maximize threading potential, but have to throttle * thread creation. what is our parallelization limit? */ throttle = 1; /* any "zero" limit scopes propagate upward */ while (parent->lim == 0 && parent->id > 0) { parent = parallel_mapping(PARALLEL_GET, parent->parent, ncpu); } /* if the top-most parent is unspecified, use all available cpus */ if (parent->lim == 0) { ncpu = bu_avail_cpus(); } else { ncpu = parent->lim; } /* starting a "zero" bu_parallel means we get one worker * thread back (for this thread) */ bu_semaphore_acquire(BU_SEM_THREAD); if (parent->started > 0) parent->started--; bu_semaphore_release(BU_SEM_THREAD); } else if (ncpu == 1) { /* single cpu case bypasses nearly everything, just invoke */ (*func)(0, arg); parallel_mapping(PARALLEL_PUT, bu_parallel_id(), 0); return; } thread_context = (struct thread_data *)bu_calloc(ncpu, sizeof(*thread_context), "struct thread_data *thread_context"); /* Fill in the data of thread_context structures of all threads */ for (x = 0; x < ncpu; x++) { struct parallel_info *next = parallel_mapping(PARALLEL_GET, -1, ncpu); thread_context[x].user_func = func; thread_context[x].user_arg = arg; thread_context[x].cpu_id = next->id; thread_context[x].affinity = affinity; thread_context[x].parent = parent; } /* * multithreading support for SunOS 5.X / Solaris 2.x */ # if defined(SUNOS) && SUNOS >= 52 nthreadc = 0; /* Give the thread system a hint... */ { static size_t concurrency = 0; /* Max concurrency we have set */ if (ncpu > concurrency) { if (thr_setconcurrency((int)ncpu)) { bu_log("ERROR parallel.c/bu_parallel(): thr_setconcurrency(%zd) failed\n", ncpu); /* Not much to do, lump it */ } else { concurrency = ncpu; } } } /* Create the threads */ for (x = 0; x < ncpu; x++) { parallel_wait_for_slot(throttle, parent, ncpu); if (thr_create(0, 0, (void *(*)(void *))parallel_interface_arg, &thread_context[x], 0, &thread)) { bu_log("ERROR: bu_parallel: thr_create(0x0, 0x0, 0x%x, 0x0, 0, 0x%x) failed for processor thread # %d\n", parallel_interface_arg, &thread, x); /* Not much to do, lump it */ } else { if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(): created thread: (thread: 0x%x) (loop:%d) (nthreadc:%zu)\n", thread, x, nthreadc); thread_tbl[nthreadc] = thread; nthreadc++; } } if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) for (i = 0; i < nthreadc; i++) bu_log("bu_parallel(): thread_tbl[%d] = 0x%x\n", i, thread_tbl[i]); /* * Wait for completion of all threads. We don't wait for threads * in order. We wait for any old thread but we keep track of how * many have returned and whether it is one that we started */ nthreade = 0; for (x = 0; x < nthreadc; x++) { if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(): waiting for thread to complete:\t(loop:%d) (nthreadc:%zu) (nthreade:%zu)\n", x, nthreadc, nthreade); if (thr_join((rt_thread_t)0, &thread, NULL)) { /* badness happened */ perror("thr_join"); bu_log("thr_join() failed"); } /* Check to see if this is one the threads we created */ for (i = 0; i < nthreadc; i++) { if (thread_tbl[i] == thread) { thread_tbl[i] = (rt_thread_t)-1; nthreade++; break; } } if ((thread_tbl[i] != (rt_thread_t)-1) && i < nthreadc) { bu_log("bu_parallel(): unknown thread %d completed.\n", thread); } if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(): thread completed: (thread: %d)\t(loop:%d) (nthreadc:%zu) (nthreade:%zu)\n", thread, x, nthreadc, nthreade); } if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(): %zu threads created. %zud threads exited.\n", nthreadc, nthreade); # endif /* SUNOS */ # if defined(HAVE_PTHREAD_H) /* Create the posix threads. * * Start at 1 so we can treat the parent as thread 0. */ nthreadc = 0; for (x = 0; x < ncpu; x++) { pthread_attr_t attrs; pthread_attr_init(&attrs); pthread_attr_setstacksize(&attrs, 10*1024*1024); parallel_wait_for_slot(throttle, parent, ncpu); if (pthread_create(&thread, &attrs, (void *(*)(void *))parallel_interface_arg, &thread_context[x])) { bu_log("ERROR: bu_parallel: pthread_create(0x0, 0x0, 0x%lx, 0x0, 0, %p) failed for processor thread # %zu\n", (unsigned long int)parallel_interface_arg, (void *)&thread, x); } else { if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) { bu_log("bu_parallel(): created thread: (thread: %p) (loop: %zu) (nthreadc: %zu)\n", (void*)thread, x, nthreadc); } thread_tbl[nthreadc] = thread; nthreadc++; } /* done with the attributes after create */ pthread_attr_destroy(&attrs); } if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) { for (i = 0; i < nthreadc; i++) { bu_log("bu_parallel(): thread_tbl[%d] = %p\n", i, (void *)thread_tbl[i]); } # ifdef SIGINFO /* may be BSD-only (calls _thread_dump_info()) */ raise(SIGINFO); # endif } /* * Wait for completion of all threads. * Wait for them in order. */ nthreade = 0; for (x = 0; x < nthreadc; x++) { int ret; if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(): waiting for thread %p to complete:\t(loop:%d) (nthreadc:%zu) (nthreade:%zu)\n", (void *)thread_tbl[x], x, nthreadc, nthreade); if ((ret = pthread_join(thread_tbl[x], NULL)) != 0) { /* badness happened */ bu_log("pthread_join(thread_tbl[%d]=%p) ret=%d\n", x, (void *)thread_tbl[x], ret); } nthreade++; thread = thread_tbl[x]; thread_tbl[x] = (rt_thread_t)-1; if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(): thread completed: (thread: %p)\t(loop:%zu) (nthreadc:%zu) (nthreade:%zu)\n", (void *)thread, x, nthreadc, nthreade); } if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(): %zu threads created. %zu threads exited.\n", nthreadc, nthreade); # endif /* end if posix threads */ # ifdef WIN32 /* Create the Win32 threads */ nthreadc = 0; for (i = 0; i < ncpu; i++) { parallel_wait_for_slot(throttle, parent, ncpu); thread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)parallel_interface_arg_stub, &thread_context[i], 0, NULL); thread_tbl[i] = thread; nthreadc++; /* Ensure that all successfully created threads are in sequential order.*/ if (thread_tbl[i] == NULL) { bu_log("bu_parallel(): Error in CreateThread, Win32 error code %d.\n", GetLastError()); --nthreadc; } } { /* Wait for other threads in the array */ DWORD returnCode; returnCode = WaitForMultipleObjects((DWORD)nthreadc, thread_tbl, TRUE, INFINITE); if (returnCode == WAIT_FAILED) { bu_log("bu_parallel(): Error in WaitForMultipleObjects, Win32 error code %d.\n", GetLastError()); } } nthreade = 0; for (x = 0; x < nthreadc; x++) { int ret; if ((ret = CloseHandle(thread_tbl[x]) == 0)) { /* Thread didn't close properly if return value is zero; don't retry and potentially loop forever. */ bu_log("bu_parallel(): Error closing thread %zu of %zu, Win32 error code %d.\n", x, nthreadc, GetLastError()); } nthreade++; thread_tbl[x] = (rt_thread_t)-1; } # endif /* end if Win32 threads */ parallel_mapping(PARALLEL_PUT, bu_parallel_id(), 0); if (UNLIKELY(bu_debug & BU_DEBUG_PARALLEL)) bu_log("bu_parallel(%zd) complete\n", ncpu); bu_free(thread_context, "struct thread_data *thread_context"); #endif /* PARALLEL */ return; }
WRAPPER(int, pthread_create, pthread_t *thr, const pthread_attr_t *attr, void * (*start) (void *), void *arg) { DECLARE(int, munmap, void *p, size_t l); DECLARE(void *, mmap, void *p, size_t l, int prot, int flags, int fd, off_t of); DECLARE(int, pthread_create, pthread_t *thr, const pthread_attr_t *attr, void * (*start) (void *), void *arg); int result; pthread_attr_t override_attr; void *override_stack; size_t override_stacksize; void *override_stack_alloc = (void *) 0; size_t override_stacksize_alloc = 0; unsigned i; TRACE ("pthread_create\n"); /* Garbage-collect dead threads' stacks. */ LOCKTH (); for (i = 0; i < LIBMUDFLAPTH_THREADS_MAX; i++) { struct pthread_info *pi = & __mf_pthread_info [i]; if (! pi->used_p) continue; if (! pi->dead_p) continue; /* VERBOSE_TRACE ("thread %u pi %p stack cleanup deferred (%u)\n", (unsigned) pi->self, pi, pi->dead_p); */ /* Delay actual deallocation by a few cycles, try to discourage the race mentioned at the end of __mf_pthread_spawner(). */ if (pi->dead_p) pi->dead_p ++; if (pi->dead_p >= 10 /* XXX */) { if (pi->stack) CALL_REAL (munmap, pi->stack_alloc, pi->stack_size_alloc); VERBOSE_TRACE ("slot %u freed, stack %p\n", i, pi->stack_alloc); memset (pi, 0, sizeof (*pi)); /* One round of garbage collection is enough. */ break; } } UNLOCKTH (); /* Let's allocate a stack for this thread, if one is not already supplied by the caller. We don't want to let e.g. the linuxthreads manager thread do this allocation. */ if (attr != NULL) override_attr = *attr; else pthread_attr_init (& override_attr); /* Get supplied attributes, if any. */ /* XXX: consider using POSIX2K attr_getstack() */ if (pthread_attr_getstackaddr (& override_attr, & override_stack) != 0 || pthread_attr_getstacksize (& override_attr, & override_stacksize) != 0) { override_stack = NULL; override_stacksize = 0; } /* Do we need to allocate the new thread's stack? */ if (__mf_opts.thread_stack && override_stack == NULL) { uintptr_t alignment = 256; /* power of two */ /* Perturb the initial stack addresses slightly, to encourage threads to have nonconflicting entries in the lookup cache for their tracked stack objects. */ static unsigned perturb = 0; const unsigned perturb_delta = 32; const unsigned perturb_count = 16; perturb += perturb_delta; if (perturb > perturb_delta*perturb_count) perturb = 0; /* Use glibc x86 defaults */ /* Should have been defined in <limits.h> */ #ifndef PTHREAD_STACK_MIN #define PTHREAD_STACK_MIN 65536 #endif override_stacksize = max (PTHREAD_STACK_MIN, __mf_opts.thread_stack * 1024); #if defined(MAP_ANONYMOUS) #define MF_MAP_ANON MAP_ANONYMOUS #elif defined(MAP_ANON) #define MF_MAP_ANON MAP_ANON #endif #ifndef MAP_FAILED #define MAP_FAILED ((void *) -1) #endif #ifdef MF_MAP_ANON override_stack = CALL_REAL (mmap, NULL, override_stacksize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MF_MAP_ANON, 0, 0); #else /* Try mapping /dev/zero instead. */ { static int zerofd = -1; if (zerofd == -1) zerofd = open ("/dev/zero", O_RDWR); if (zerofd == -1) override_stack = MAP_FAILED; else override_stack = CALL_REAL (mmap, NULL, override_stacksize, PROT_READ|PROT_WRITE, MAP_PRIVATE, zerofd, 0); } #endif if (override_stack == 0 || override_stack == MAP_FAILED) { errno = EAGAIN; return -1; } VERBOSE_TRACE ("thread stack alloc %p size %lu\n", override_stack, (unsigned long) override_stacksize); /* Save the original allocated values for later deallocation. */ override_stack_alloc = override_stack; override_stacksize_alloc = override_stacksize; /* The stackaddr pthreads attribute is a candidate stack pointer. It must point near the top or the bottom of this buffer, depending on whether stack grows downward or upward, and suitably aligned. On the x86, it grows down, so we set stackaddr near the top. */ /* XXX: port logic */ override_stack = (void *) (((uintptr_t) override_stack + override_stacksize - alignment - perturb) & (~(uintptr_t)(alignment-1))); /* XXX: consider using POSIX2K attr_setstack() */ if (pthread_attr_setstackaddr (& override_attr, override_stack) != 0 || pthread_attr_setstacksize (& override_attr, override_stacksize - alignment - perturb) != 0) { /* This should not happen. */ CALL_REAL (munmap, override_stack, override_stacksize); errno = EAGAIN; return -1; } } /* Actually start the child thread. */ { struct pthread_start_info psi; struct pthread_info *pi = NULL; /* Fill in startup-control fields. */ psi.user_fn = start; psi.user_arg = arg; psi.thread_info = NULL; /* Actually create the thread. */ __mf_state = reentrant; result = CALL_REAL (pthread_create, thr, & override_attr, & __mf_pthread_spawner, (void *) & psi); __mf_state = active; /* We also hook pthread_join/pthread_exit to get into reentrant mode during thread shutdown/cleanup. */ /* Wait until child thread has progressed far enough into its __mf_pthread_spawner() call. */ while (1) /* XXX: timeout? */ { volatile struct pthread_start_info *psip = & psi; pi = psip->thread_info; if (pi != NULL) break; sched_yield (); } /* Fill in remaining fields in pthread_info. */ pi->stack = override_stack; pi->stack_size = override_stacksize; pi->stack_alloc = override_stack_alloc; pi->stack_size_alloc = override_stacksize_alloc; /* XXX: this might be too late for future heuristics that attempt to use thread stack bounds. We may need to put the new thread to sleep. */ } /* May need to clean up if we created a pthread_attr_t of our own. */ if (attr == NULL) pthread_attr_destroy (& override_attr); /* NB: this shouldn't deallocate stack */ return result; }
/* \param plen: the length of the current message (needed in order to be able to discard excess data in the message, if present) */ pcap_t *daemon_startcapture(SOCKET sockctrl, pthread_t *threaddata, char *source, int active, struct rpcap_sampling *samp_param, uint32 plen, char *errbuf) { char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer pcap_t *fp= NULL; // pcap_t main variable unsigned int nread; // number of bytes of the payload read from the socket char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx= 0; // index which keeps the number of bytes currently buffered // socket-related variables SOCKET sockdata= 0; // socket descriptor of the data connection struct addrinfo hints; // temp, needed to open a socket connection struct addrinfo *addrinfo; // temp, needed to open a socket connection struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine pthread_attr_t detachedAttribute; // temp, needed to set the created thread as detached // RPCAP-related variables struct rpcap_startcapreq startcapreq; // start capture request message struct rpcap_startcapreply *startcapreply; // start capture reply message int serveropen_dp; // keeps who is going to open the data connection addrinfo= NULL; if ( (nread= sock_recv(sockctrl, (char *) &startcapreq, sizeof(struct rpcap_startcapreq), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) return NULL; startcapreq.flags= ntohs(startcapreq.flags); // Open the selected device if ( (fp= pcap_open(source, ntohl(startcapreq.snaplen), (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? PCAP_OPENFLAG_PROMISCUOUS : 0 /* local device, other flags not needed */, ntohl(startcapreq.read_timeout), NULL /* local device, so no auth */, errbuf)) == NULL) { rpcap_senderror(sockctrl, errbuf, PCAP_ERR_OPEN, NULL); return NULL; } // Apply sampling parameters fp->rmt_samp.method= samp_param->method; fp->rmt_samp.value= samp_param->value; /* We're in active mode if: - we're using TCP, and the user wants us to be in active mode - we're using UDP */ serveropen_dp= (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || active; /* Gets the sockaddr structure referred to the other peer in the ctrl connection We need that because: - if we're in passive mode, we need to know the address family we want to use (the same used for the ctrl socket) - if we're in active mode, we need to know the network address of the other host we want to connect to */ saddrlen = sizeof(struct sockaddr_storage); if (getpeername(sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getpeername(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } memset(&hints, 0, sizeof(struct addrinfo) ); hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; hints.ai_family = saddr.ss_family; // Now we have to create a new socket to send packets if (serveropen_dp) // Data connection is opened by the server toward the client { sprintf(portdata, "%d", ntohs(startcapreq.portdata) ); // Get the name of the other peer (needed to connect to that specific network address) if (getnameinfo( (struct sockaddr *) &saddr, saddrlen, peerhost, sizeof(peerhost), NULL, 0, NI_NUMERICHOST) ) { sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ( (sockdata= sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == -1) goto error; } else // Data connection is opened by the client toward the server { hints.ai_flags = AI_PASSIVE; // Let's the server socket pick up a free network port for us if (sock_initaddress(NULL, "0", &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ( (sockdata= sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errbuf, PCAP_ERRBUF_SIZE)) == -1) goto error; // get the complete sockaddr structure used in the data connection saddrlen = sizeof(struct sockaddr_storage); if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getsockname(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } // Get the local port the system picked up if (getnameinfo( (struct sockaddr *) &saddr, saddrlen, NULL, 0, portdata, sizeof(portdata), NI_NUMERICSERV) ) { sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } } // addrinfo is no longer used freeaddrinfo(addrinfo); addrinfo= NULL; // save the socket ID for the next calls fp->rmt_sockctrl= sockctrl; // Needed to send an error on the ctrl connection // Now I can set the filter if ( daemon_unpackapplyfilter(fp, &nread, &plen, errbuf) ) goto error; // Now, I can send a RPCAP start capture reply message if ( sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr( (struct rpcap_header *) sendbuf, RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply) ); startcapreply= (struct rpcap_startcapreply *) &sendbuf[sendbufidx]; if ( sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(startcapreply, 0, sizeof(struct rpcap_startcapreply) ); startcapreply->bufsize= htonl(fp->bufsize); if (!serveropen_dp) { unsigned short port = (unsigned short)strtoul(portdata,NULL,10); startcapreply->portdata= htons(port); } if ( sock_send(sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if (!serveropen_dp) { SOCKET socktemp; // We need another socket, since we're going to accept() a connection // Connection creation saddrlen = sizeof(struct sockaddr_storage); socktemp= accept(sockdata, (struct sockaddr *) &saddr, &saddrlen); if (socktemp == -1) { sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } // Now that I accepted the connection, the server socket is no longer needed sock_close(sockdata, errbuf, PCAP_ERRBUF_SIZE); sockdata= socktemp; } fp->rmt_sockdata= sockdata; /* GV we need this to create the thread as detached. */ /* GV otherwise, the thread handle is not destroyed */ pthread_attr_init(&detachedAttribute); pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED); // Now we have to create a new thread to receive packets if ( pthread_create(threaddata, &detachedAttribute, (void *) daemon_thrdatamain, (void *) fp) ) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread"); pthread_attr_destroy(&detachedAttribute); goto error; } pthread_attr_destroy(&detachedAttribute); // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); return fp; error: rpcap_senderror(sockctrl, errbuf, PCAP_ERR_STARTCAPTURE, NULL); if (addrinfo) freeaddrinfo(addrinfo); if (threaddata) pthread_cancel(*threaddata); if (sockdata) sock_close(sockdata, NULL, 0); // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); if (fp) { pcap_close(fp); fp= NULL; } return NULL; }
int main(int argc, char* argv[]) { pthread_t* threads; int* tids; pthread_attr_t attr; int ret; int mix_sig, i; /* Parse arguments */ if(argc < 2) { fprintf(stderr, "%s <numProcesors> <maxLoop>\n", argv[0]); exit(1); } NumProcs = atoi(argv[1]); assert(NumProcs > 0 && NumProcs <= 32); if (argc >= 3) { MaxLoop = atoi(argv[2]); assert(MaxLoop > 0); } /* Initialize the mix array */ for(i = 0; i < MAX_ELEM; i++) { m[i].value = mix(i,i); } /* Initialize barrier counter */ startCounter = NumProcs; /* Initialize array of thread structures */ threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs); assert(threads != NULL); tids = (int *) malloc(sizeof (int) * NumProcs); assert(tids != NULL); /* Initialize thread attribute */ pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); ret = pthread_mutex_init(&threadLock, NULL); assert(ret == 0); for(i=0; i < NumProcs; i++) { /* ************************************************************ * pthread_create takes 4 parameters * p1: threads(output) * p2: thread attribute * p3: start routine, where new thread begins * p4: arguments to the thread * ************************************************************ */ tids[i] = i+1; ret = pthread_create(&threads[i], &attr, ThreadBody, &tids[i]); assert(ret == 0); } /* Wait for each of the threads to terminate */ for(i=0; i < NumProcs; i++) { ret = pthread_join(threads[i], NULL); assert(ret == 0); } /* compute the result */ mix_sig = sig[0]; for(i = 1; i < NumProcs ; i++) { mix_sig = mix(sig[i], mix_sig); } /* end of parallel phase */ /* ************************************************************ * print results * 1. mix_sig : deterministic race? * 2. &mix_sig : deterministic stack layout? * 3. malloc : deterministic heap layout? * ************************************************************ */ printf("\n\nShort signature: %08x @ %p @ %p\n\n\n", mix_sig, &mix_sig, (void*)malloc(PAGE_SIZE/5)); fflush(stdout); usleep(5); pthread_mutex_destroy(&threadLock); pthread_attr_destroy(&attr); return 0; }
VCOS_STATUS_T vcos_thread_create(VCOS_THREAD_T *thread, const char *name, VCOS_THREAD_ATTR_T *attrs, VCOS_THREAD_ENTRY_FN_T entry, void *arg) { VCOS_STATUS_T st; pthread_attr_t pt_attrs; VCOS_THREAD_ATTR_T *local_attrs = attrs ? attrs : &default_attrs; int rc; vcos_assert(thread); memset(thread, 0, sizeof(VCOS_THREAD_T)); rc = pthread_attr_init(&pt_attrs); if (rc < 0) return VCOS_ENOMEM; st = vcos_semaphore_create(&thread->suspend, NULL, 0); if (st != VCOS_SUCCESS) { pthread_attr_destroy(&pt_attrs); return st; } pthread_attr_setstacksize(&pt_attrs, local_attrs->ta_stacksz); #if VCOS_CAN_SET_STACK_ADDR if (local_attrs->ta_stackaddr) { pthread_attr_setstackaddr(&pt_attrs, local_attrs->ta_stackaddr); } #else vcos_demand(local_attrs->ta_stackaddr == 0); #endif /* pthread_attr_setpriority(&pt_attrs, local_attrs->ta_priority); */ vcos_assert(local_attrs->ta_stackaddr == 0); /* Not possible */ thread->entry = entry; thread->arg = arg; thread->legacy = local_attrs->legacy; strncpy(thread->name, name, sizeof(thread->name)); thread->name[sizeof(thread->name)-1] = '\0'; memset(thread->at_exit, 0, sizeof(thread->at_exit)); rc = pthread_create(&thread->thread, &pt_attrs, vcos_thread_entry, thread); pthread_attr_destroy(&pt_attrs); if (rc < 0) { vcos_semaphore_delete(&thread->suspend); return VCOS_ENOMEM; } else { return VCOS_SUCCESS; } }
int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*start) (void *), void *parameter) { int result; void *stack; char name[RT_NAME_MAX]; static rt_uint16_t pthread_number = 0; _pthread_data_t *ptd; /* tid shall be provided */ RT_ASSERT(tid != RT_NULL); /* allocate posix thread data */ ptd = (_pthread_data_t*)rt_malloc(sizeof(_pthread_data_t)); if (ptd == RT_NULL) return ENOMEM; /* clean posix thread data memory */ rt_memset(ptd, 0, sizeof(_pthread_data_t)); ptd->canceled = 0; ptd->cancelstate = PTHREAD_CANCEL_DISABLE; ptd->canceltype = PTHREAD_CANCEL_DEFERRED; ptd->magic = PTHREAD_MAGIC; if (attr != RT_NULL) ptd->attr = *attr; else { /* use default attribute */ pthread_attr_init(&ptd->attr); } rt_snprintf(name, sizeof(name), "pth%02d", pthread_number ++); if (ptd->attr.stack_base == 0) { stack = (void*)rt_malloc(ptd->attr.stack_size); } else stack = (void*)(ptd->attr.stack_base); if (stack == RT_NULL) { rt_free(ptd); return ENOMEM; } /* pthread is a static thread object */ ptd->tid = (rt_thread_t) rt_malloc(sizeof(struct rt_thread)); if (ptd->tid == RT_NULL) { if (ptd->attr.stack_base == 0) rt_free(stack); rt_free(ptd); return ENOMEM; } if (ptd->attr.detachstate == PTHREAD_CREATE_JOINABLE) { ptd->joinable_sem = rt_sem_create(name, 0, RT_IPC_FLAG_FIFO); if (ptd->joinable_sem == RT_NULL) { if (ptd->attr.stack_base != 0) rt_free(stack); rt_free(ptd); return ENOMEM; } } else ptd->joinable_sem = RT_NULL; /* set parameter */ ptd->thread_entry = start; ptd->thread_parameter = parameter; /* initial this pthread to system */ if (rt_thread_init(ptd->tid, name, pthread_entry_stub, ptd, stack, ptd->attr.stack_size, ptd->attr.priority, 5) != RT_EOK) { if (ptd->attr.stack_base == 0) rt_free(stack); if (ptd->joinable_sem != RT_NULL) rt_sem_delete(ptd->joinable_sem); rt_free(ptd); return EINVAL; } /* set pthread id */ *tid = ptd->tid; /* set pthread cleanup function and ptd data */ (*tid)->cleanup = _pthread_cleanup; (*tid)->user_data = (rt_uint32_t)ptd; /* start thread */ result = rt_thread_startup(*tid); if (result == RT_EOK) return 0; /* start thread failed */ rt_thread_detach(ptd->tid); if (ptd->attr.stack_base == 0) rt_free(stack); if (ptd->joinable_sem != RT_NULL) rt_sem_delete(ptd->joinable_sem); rt_free(ptd); return EINVAL; }
main() { int fromlen; int i, s, ns, len; struct sockaddr_un saun, fsaun; for(i=0 ;i<3; i++) idleThread[i] = i; for(i=0; i<3;i++) initialiseConnection(i); if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("server: socket"); exit(1); } saun.sun_family = AF_UNIX; strcpy(saun.sun_path, ADDRESS); unlink(ADDRESS); len = sizeof(saun.sun_family) + strlen(saun.sun_path); if (bind(s, &saun, len) < 0) { perror("server: bind"); exit(1); } if (listen(s, 5) < 0) { perror("server: listen"); exit(1); } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); while(1){ ns = accept(s, (struct sockadd*)&fsaun, &fromlen); if (ns < 0) { perror("server: accept"); exit(1); } int curthread = comeBackYesterday(); //int curthread = merryGoRound(); int par[2]={ns,curthread}; active++; if(pthread_create(&thread[curthread],NULL,connectToClient,(void*)par)){ perror("server: cant create thread"); exit(1); } printf("Sent to server : %d\n",curthread); pthread_detach(thread[curthread]); /*while(active>=No_of_servers){ //puts("come back yesterday"); }*/ } if (ns < 0) { perror("server: accept"); exit(1); } close(s); return 0; }
TSExec::TSExec() { pthread_attr_init(&fAttr); }
/*---------------------------------------------------------------------+ | main | | ==================================================================== | | | | Function: Main program (see prolog for more details) | | | | Returns: (0) Successful completion | | (-1) Error occurred | | | +---------------------------------------------------------------------*/ int main (int argc, char **argv) { pthread_attr_t newattr; int i; /* Misc loop index */ int j; /* Misc loop index */ int k; /* Misc loop index */ size_t Size; /* Size (in bytes) of shared memory segment*/ unsigned long *ulptr; /* Misc pointer */ /* Index into shared memory segment */ /* * Parse command line arguments and print out program header */ parse_args (argc, argv); printf ("%s: IPC Shared Memory TestSuite program\n", *argv); /* * Show options in effect. */ printf ("\tNumber of writers = %d\n", num_writers); printf ("\tNumber of readers = %d\n", num_readers); printf ("\tBytes per writer = %d\n", buffer_size); /*---------------------------------------------------------------------+ | shared memory segments | +---------------------------------------------------------------------*/ for (i=0; i<num_writers; i++) { /* * Obtain a unique shared memory identifier with shmget (). * Attach the shared memory segment to the process with shmat (). */ j=i*3; Size=sizeof (int); /* * Create a shared memory segment for storing the read count * (number of reader threads reading shared data) * After creating the shared memory segment, initialize it. */ if ((shmid[j] = shmget (IPC_PRIVATE, Size, SHMEM_MODE)) < 0) sys_error ("read_count shmget failed", __LINE__); if ((long)(read_count[i] = (int *) shmat (shmid[j], 0, 0)) == -1) sys_error ("shmat failed", __LINE__); *(read_count[i]) = 0; /* * Create a shared memory segment for storing the checksums of readers. * After creating the shared memory segment, initialize it. */ j++; Size=sizeof (unsigned long) * num_readers; if ((shmid[j] = shmget (IPC_PRIVATE, Size, SHMEM_MODE)) < 0) sys_error ("checksum shmget failed", __LINE__); if ((long)(checksum[i] = (unsigned long *) shmat (shmid[j], 0, 0)) == -1) sys_error ("shmat failed", __LINE__); ulptr=checksum[i]; for (k=0; k < num_readers; k++) { *ulptr = 0; ulptr++; } /* * Create the "scratch" shared memory segment for storing * a series of values . */ Size=buffer_size; j++; if ((shmid[j] = shmget (IPC_PRIVATE, Size, SHMEM_MODE)) < 0) sys_error ("shmptr shmget failed", __LINE__); if ((long)(shmptr[i] = shmat (shmid[j], 0, 0)) == -1) sys_error ("shmat failed", __LINE__); } /*---------------------------------------------------------------------+ | Threads | +---------------------------------------------------------------------*/ /* * Create threads array... */ writer_th = (pthread_t *) malloc ((size_t) (num_writers * sizeof (pthread_t))); reader_th = (pthread_t *) malloc ((size_t) (num_writers * num_readers * sizeof (pthread_t))); /* * Initializes mutexes and sets their attributes */ for (i=0; i<num_writers; i++) { if (pthread_mutex_init(&mutex_r[i] , (pthread_mutexattr_t *)NULL) != 0) sys_error ("Can't initialize mutex_r", __LINE__); if (pthread_mutex_init (&cond_mutex[i], (pthread_mutexattr_t *)NULL)) sys_error ("Can't initialize cond_mutex", __LINE__); if (pthread_cond_init (&cond_var[i], (pthread_condattr_t *)NULL)) sys_error ("cond_init(&cond_var) failed", __LINE__); /* * lock the access to the shared memory data segment -- * get lock now to insure the writer gets first access to the segment. * */ thread_hold[i]=1; } /* * Creates a thread attributes object and initializes it * with default values. */ if (pthread_attr_init(&newattr)) sys_error ("attr_init(&newattr) failed", __LINE__); /* * Sets the value of the detachstate attribute of a thread attributes * object : * PTHREAD_CREATE_UNDETACHED Specifies that the thread will be * created in undetached state. */ #ifdef _LINUX_ // the DEFAULT state for linux pthread_create is to be "undetatched" or joinable /* if (pthread_attr_setdetachstate (&newattr, PTHREAD_CREATE_JOINABLE)) sys_error ("attr_setdetachstate(&newattr) failed", __LINE__);*/ #else if (pthread_attr_setdetachstate (&newattr, PTHREAD_CREATE_UNDETACHED)) sys_error ("attr_setdetachstate(&newattr) failed", __LINE__); #endif /* * Create all num_writers threads . Each writer thread will fill * the "scratch" shared memory segment (shmptr) up with data and * will store the result in cksum array accessible by the main. */ for (i = 0; i < num_writers; i++) { if (pthread_create (&writer_th[i], &newattr, writer, (void *) (long)i)) sys_error ("writer: pthread_create failed", __LINE__); /* * Create all num_readers threads . Each reader thread will compute * the checksum of the shared memory segment (shmptr) and will store * the result in the other shared memory segment (checksum)accessible * by the writer. */ k=i*num_readers; for (j = k; j < (k + num_readers) ; j++) { if (pthread_create (&reader_th[j], &newattr, reader, (void *) (long)j)) sys_error ("reader: pthread_create failed", __LINE__); } } for (i = 0; i < num_writers; i++) { if (pthread_join( writer_th[i], NULL)) { printf("writer_th: pthread_join return: %d\n",i); sys_error("pthread_join bad status", __LINE__); } /* * Wait for the reader threads to compute the checksums and complete. */ k=i*num_readers; for (j = k; j < (k + num_readers) ; j++) { if (pthread_join( reader_th[j], NULL)) { printf("reader_th: pthread_join return: %d\n",j); sys_error("pthread_join bad status", __LINE__); } } } /* * After the threads complete, check their exit status to insure * that they ran to completion and then verify the corresponding * checksum. */ for (i = 0; i < num_writers; i++) { ulptr=checksum[i]; for (j=0; j<num_readers; j++) { if (cksum[i] != *ulptr ) error ("checksums do not match", __LINE__); } } printf ("\n\tMain: readers calculated segment successfully\n"); release(); printf ("\nsuccessful!\n"); return (0); }
int main(int argc, const char * argv[]) { pthread_t tid1, tid2; param p1, p2; pthread_attr_t attr; int detachstate, scope, sched, algoritmo; size_t stacksize; p1.tid = 1; strcpy(p1.nombre, "Hilo 1"); p2.tid = 2; strcpy(p2.nombre, "Hilo 2"); pthread_key_create(&tsd, NULL); pthread_attr_init(&attr); pthread_attr_getdetachstate(&attr, &detachstate); pthread_attr_getscope(&attr, &scope); pthread_attr_getstacksize(&attr, &stacksize); pthread_attr_getschedpolicy(&attr, &algoritmo); pthread_attr_getinheritsched(&attr, &sched); printf("Hilo 1 creado con valores siguientes: \n"); printf("Valores iniciales de atributos: \n"); printf("DETACHSTATE = %d \n", detachstate); printf("SCOPE = %d \n", scope); printf("STACKSIZE = %zu bytes\n", stacksize); printf("SCHEDPOLICY = %d \n", algoritmo); printf("INHERSCHED = %d \n", sched); pthread_create(&tid1, &attr, hilo, (void *) &p1); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setschedpolicy(&attr, SCHED_FIFO); pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED); printf("Hilo 2 creado con valores siguientes: \n"); pthread_attr_getdetachstate(&attr, &detachstate); pthread_attr_getscope(&attr, &scope); pthread_attr_getstacksize(&attr, &stacksize); pthread_attr_getschedpolicy(&attr, &algoritmo); pthread_attr_getinheritsched(&attr, &sched); printf("Valores iniciales de atributos: \n"); printf("DETACHSTATE = %d \n", detachstate); printf("SCOPE = %d \n", scope); printf("STACKSIZE = %zu bytes\n", stacksize); printf("SCHEDPOLICY = %d \n", algoritmo); printf("INHERSCHED = %d \n", sched); pthread_create(&tid2, &attr, hilo, (void *) &p2); if (pthread_equal(tid1, tid2)) { printf(" Son iguales \n"); } else { printf("Son diferentes \n"); } pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_key_delete(tsd); pthread_attr_destroy(&attr); pthread_exit(NULL); return 0; }
void priority_inheritance(void) { #if defined(CONFIG_PRIORITY_INHERITANCE) && !defined(CONFIG_DISABLE_SIGNALS) && !defined(CONFIG_DISABLE_PTHREAD) pthread_t lowpri[NLOWPRI_THREADS]; pthread_t medpri; pthread_t highpri[NHIGHPRI_THREADS]; pthread_addr_t result; pthread_attr_t attr; struct sched_param sparam; int my_pri; int status; int i; printf("priority_inheritance: Started\n"); g_middlestate = NOTSTARTED; for (i = 0; i < NHIGHPRI_THREADS; i++) g_highstate[i] = NOTSTARTED; for (i = 0; i < NLOWPRI_THREADS; i++) g_lowstate[i] = NOTSTARTED; status = sched_getparam (getpid(), &sparam); if (status != 0) { printf("priority_inheritance: sched_getparam failed\n"); sparam.sched_priority = PTHREAD_DEFAULT_PRIORITY; } my_pri = sparam.sched_priority; g_highpri = sched_get_priority_max(SCHED_FIFO); g_lowpri = sched_get_priority_min(SCHED_FIFO); g_medpri = my_pri - 1; sem_init(&g_sem, 0, NLOWPRI_THREADS); dump_nfreeholders("priority_inheritance:"); /* Start the low priority threads */ for (i = 0; i < NLOWPRI_THREADS; i++) { int threadno = i+1; printf("priority_inheritance: Starting lowpri_thread-%d (of %d) at %d\n", threadno, NLOWPRI_THREADS, g_lowpri); status = pthread_attr_init(&attr); if (status != 0) { printf("priority_inheritance: pthread_attr_init failed, status=%d\n", status); } sparam.sched_priority = g_lowpri; status = pthread_attr_setschedparam(&attr,& sparam); if (status != OK) { printf("priority_inheritance: pthread_attr_setschedparam failed, status=%d\n", status); } else { printf("priority_inheritance: Set lowpri_thread-%d priority to %d\n", threadno, sparam.sched_priority); } status = pthread_create(&lowpri[i], &attr, lowpri_thread, (void*)threadno); if (status != 0) { printf("priority_inheritance: pthread_create failed, status=%d\n", status); } } printf("priority_inheritance: Waiting...\n"); sleep(2); dump_nfreeholders("priority_inheritance:"); /* Start the medium priority thread */ printf("priority_inheritance: Starting medpri_thread at %d\n", g_medpri); status = pthread_attr_init(&attr); if (status != 0) { printf("priority_inheritance: pthread_attr_init failed, status=%d\n", status); } sparam.sched_priority = g_medpri; status = pthread_attr_setschedparam(&attr,& sparam); if (status != OK) { printf("priority_inheritance: pthread_attr_setschedparam failed, status=%d\n", status); } else { printf("priority_inheritance: Set medpri_thread priority to %d\n", sparam.sched_priority); } fflush(stdout); status = pthread_create(&medpri, &attr, medpri_thread, NULL); if (status != 0) { printf("priority_inheritance: pthread_create failed, status=%d\n", status); } printf("priority_inheritance: Waiting...\n"); sleep(1); dump_nfreeholders("priority_inheritance:"); /* Start the high priority threads */ for (i = 0; i < NHIGHPRI_THREADS; i++) { int threadno = i+1; printf("priority_inheritance: Starting highpri_thread-%d (of %d) at %d\n", threadno, NHIGHPRI_THREADS, g_highpri); status = pthread_attr_init(&attr); if (status != 0) { printf("priority_inheritance: pthread_attr_init failed, status=%d\n", status); } sparam.sched_priority = g_highpri - i; status = pthread_attr_setschedparam(&attr,& sparam); if (status != OK) { printf("priority_inheritance: pthread_attr_setschedparam failed, status=%d\n", status); } else { printf("priority_inheritance: Set highpri_thread-%d priority to %d\n", threadno, sparam.sched_priority); } fflush(stdout); status = pthread_create(&highpri[i], &attr, highpri_thread, (void*)threadno); if (status != 0) { printf("priority_inheritance: pthread_create failed, status=%d\n", status); } } dump_nfreeholders("priority_inheritance:"); fflush(stdout); /* Wait for all thread instances to complete */ for (i = 0; i < NHIGHPRI_THREADS; i++) { printf("priority_inheritance: Waiting for highpri_thread-%d to complete\n", i+1); fflush(stdout); (void)pthread_join(highpri[i], &result); dump_nfreeholders("priority_inheritance:"); } printf("priority_inheritance: Waiting for medpri_thread to complete\n"); fflush(stdout); (void)pthread_join(medpri, &result); dump_nfreeholders("priority_inheritance:"); for (i = 0; i < NLOWPRI_THREADS; i++) { printf("priority_inheritance: Waiting for lowpri_thread-%d to complete\n", i+1); fflush(stdout); (void)pthread_join(lowpri[i], &result); dump_nfreeholders("priority_inheritance:"); } printf("priority_inheritance: Finished\n"); sem_destroy(&g_sem); dump_nfreeholders("priority_inheritance:"); fflush(stdout); #endif /* CONFIG_PRIORITY_INHERITANCE && !CONFIG_DISABLE_SIGNALS && !CONFIG_DISABLE_PTHREAD */ }
/* * Get the initial address and size of current thread's stack */ static int get_stack(void **addr, size_t *size) { #define CHECK_ERR(expr) \ {int err = (expr); if (err) return err;} #if defined HAVE_PTHREAD_GETATTR_NP || defined HAVE_PTHREAD_ATTR_GET_NP || \ (defined HAVE_PTHREAD_GET_STACKADDR_NP && defined HAVE_PTHREAD_GET_STACKSIZE_NP) pthread_attr_t attr; size_t guard = 0; # ifdef HAVE_PTHREAD_GETATTR_NP /* Linux */ STACK_GROW_DIR_DETECTION; CHECK_ERR(pthread_getattr_np(pthread_self(), &attr)); # ifdef HAVE_PTHREAD_ATTR_GETSTACK CHECK_ERR(pthread_attr_getstack(&attr, addr, size)); STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size)); # else CHECK_ERR(pthread_attr_getstackaddr(&attr, addr)); CHECK_ERR(pthread_attr_getstacksize(&attr, size)); # endif # elif defined HAVE_PTHREAD_ATTR_GET_NP /* FreeBSD, DragonFly BSD, NetBSD */ CHECK_ERR(pthread_attr_init(&attr)); CHECK_ERR(pthread_attr_get_np(pthread_self(), &attr)); # ifdef HAVE_PTHREAD_ATTR_GETSTACK CHECK_ERR(pthread_attr_getstack(&attr, addr, size)); STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size)); # else CHECK_ERR(pthread_attr_getstackaddr(&attr, addr)); CHECK_ERR(pthread_attr_getstacksize(&attr, size)); STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size)); # endif # else /* MacOS X */ pthread_t th = pthread_self(); *addr = pthread_get_stackaddr_np(th); *size = pthread_get_stacksize_np(th); CHECK_ERR(pthread_attr_init(&attr)); # endif CHECK_ERR(pthread_attr_getguardsize(&attr, &guard)); *size -= guard; pthread_attr_destroy(&attr); #elif defined HAVE_THR_STKSEGMENT || defined HAVE_PTHREAD_STACKSEG_NP stack_t stk; # if defined HAVE_THR_STKSEGMENT /* Solaris */ CHECK_ERR(thr_stksegment(&stk)); # else /* OpenBSD */ CHECK_ERR(pthread_stackseg_np(pthread_self(), &stk)); # endif *addr = stk.ss_sp; *size = stk.ss_size; #elif defined HAVE_PTHREAD_GETTHRDS_NP /* AIX */ pthread_t th = pthread_self(); struct __pthrdsinfo thinfo; char reg[256]; int regsiz=sizeof(reg); CHECK_ERR(pthread_getthrds_np(&th, PTHRDSINFO_QUERY_ALL, &thinfo, sizeof(thinfo), ®, ®siz)); *addr = thinfo.__pi_stackaddr; *size = thinfo.__pi_stacksize; STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size)); #else #error STACKADDR_AVAILABLE is defined but not implemented. #endif return 0; #undef CHECK_ERR }
// main program int main() { fp = fopen("mytest.dat", "r"); //*****************init everything: threads, sems, shmem********/// int r=0; int shmid; // shared memory ID // pthread_t producer[1]; // process id for thread 1 // pthread_t consumer[1]; // process id for thread 2 // pthread_attr_t attr; // attribute pointer array // char *shmadd; shmadd = (char *) 0; //create shared memory seg, if return -1 then print error if ((shmid = shmget (SHMKEY, sizeof(char), IPC_CREAT | 0666)) < 0) { perror ("shmget"); return (1); } //connect process to shared memory segment. If return is -1 then print error if ((buffer = (shared_mem *) shmat (shmid, shmadd, 0)) == (shared_mem *) -1) { perror ("shmat"); return (0); } //set the char buffer_array[15]; buffer->value = buffer_array; counter = (shared_dat *) malloc(sizeof(shared_dat)); // initialize shared memory to 0 // counter->value = 0 ; // initialize semaphores sem_init(&empty,0,BUFFER_SIZE); sem_init(&full,0,0); sem_init(&mutex,0,1); // flush std out fflush(stdout); pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); // system-wide contention // // Create the threads // pthread_create(&producer[0], &attr, FuncProd, 0); pthread_create(&consumer[0], &attr, FuncCons, 0); // Wait for the threads to finish // pthread_join(producer[0], 0); pthread_join(consumer[0], 0); sem_destroy(&empty); sem_destroy(&full); sem_destroy(&mutex); //release shared mem with IPC_RMID and print "end" if ((shmctl (shmid, IPC_RMID, (struct shmid_ds *) 0)) == -1) { perror ("shmctl"); exit (-1); } fclose(fp); //**************once threads finished and * reached in buffer**********/// printf("from parent counter = %d\n", counter->value); printf("---------------------------------------------------------------------------\n"); printf("\t\t End of simulation\n"); return 0; }
bool RAD_Thread::StartThread() { if(!m_StartStopLock.Acquire(5000, __FILE__, __LINE__)) return false; if(m_handle) { radlog(L_WARN, "[RAD_Thread] '%s' already started", m_ThreadName.c_str()); m_StartStopLock.Release(__FILE__, __LINE__); return false; } m_bShouldWatch = false; // prevent from watching-dogged rad_assert(m_bStop == false && m_Alive == ASUnused); int ret = StartThreadHook(); if(ret != 0) { radlog(L_WARN, "[RAD_Thread] StartThreadHook returns %d. " "The thread is not started", ret); m_bShouldWatch = true; m_StartStopLock.Release(__FILE__, __LINE__); return false; } #ifdef RAD_OS_WIN32 m_handle = _beginthreadex(NULL, // security 256*1024, // stack_size 256kb ThreadProc, this, 0, /* initflag: (0 for running or * CREATE_SUSPENDED for suspended) */ &m_thr_id); if(m_handle == 0) { /* _beginthreadex returns 0 on an error */ radlog(L_ERROR|L_CONS, "[RAD_Thread] Fail to _beginthreadex: %d %s", errno, strerror(errno)); m_bShouldWatch = true; m_StartStopLock.Release(__FILE__, __LINE__); return false; } #else pthread_attr_t attr; ret = pthread_attr_init(&attr); if(ret) radlog(L_WARN|L_CONS, "[RAD_Thread] Unable to create a thread " "attribute for '%s', rc %d", m_ThreadName.c_str(), ret); ret = pthread_attr_setstacksize(&attr, 256*1024); if(ret) radlog(L_WARN|L_CONS, "[RAD_Thread] Unable to set stack size " "on thread attribute for '%s', rc %d", m_ThreadName.c_str(), ret); ret = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); if(ret) radlog(L_WARN|L_CONS, "[RAD_Thread] Unable to set " "scope(PTHREAD_SCOPE_SYSTEM) on thread attribute " "for '%s', rc %d", m_ThreadName.c_str(), ret); ret = pthread_create((pthread_t*)&m_handle, &attr, ThreadProc, this); m_thr_id = m_handle; pthread_attr_destroy(&attr); if(ret) { radlog(L_ERROR|L_CONS, "[RAD_Thread] Fail to pthread_create: %d", ret); m_bShouldWatch = true; m_StartStopLock.Release(__FILE__, __LINE__); return false; } #endif bool rc = m_StartStopLock.Wait(3000, __FILE__, __LINE__); if(!rc) radlog(L_WARN, "[RAD_Thread] '%s' did not signal start", m_ThreadName.c_str()); else rad_assert(m_Alive == ASAlive); m_bShouldWatch = true; m_StartStopLock.Release(__FILE__, __LINE__); return true; }
/** * OSCL Proc layer function * Input Argument: * function_name = Name of the thread Function * stack_size = Size of the thread stack * argument = Argument to be passed to thread function * Thread_State = Enumeration which specifies the state of the thread on creation * with values Running and Suspend * Return value : eOsclProcError */ OSCL_EXPORT_REF OsclProcStatus::eOsclProcError OsclThread::Create(TOsclThreadFuncPtr function_name, int32 stack_size, TOsclThreadFuncArg argument, OsclThread_State state, bool oIsJoinable) { if (stack_size < 0) return OsclProcStatus::INVALID_PARAM_ERROR; if (function_name == NULL) return OsclProcStatus::INVALID_PARAM_ERROR; //Reset thread creation state, since the thread may //have exited. if (bCreated) bCreated = false; switch (state) { case Start_on_creation: break; case Suspend_on_creation: //can't create suspended pthread. return OsclProcStatus::INVALID_PARAM_ERROR; } pthread_attr_t attr; pthread_attr_init(&attr); if (stack_size != 0) pthread_attr_setstacksize(&attr, stack_size); // Default detachstate attribute to PTHREAD_CREATE_DETACHED state int detach_ret; if (oIsJoinable) { detach_ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); bJoinable = true; } else { detach_ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); bJoinable = false; } switch (detach_ret) { case 0: // successful, continue thread creation break; case EINVAL: default: return OsclProcStatus::PSHARED_ATTRIBUTE_SETTING_ERROR; } int result = pthread_create( (pthread_t*) & ObjThread, &attr, function_name, (void*)argument); switch (result) { case 0: bCreated = true; return OsclProcStatus::SUCCESS_ERROR; case EAGAIN: return OsclProcStatus::NOT_ENOUGH_RESOURCES_ERROR; default: return OsclProcStatus::OTHER_ERROR; } }
int main(int argc, char *argv[]) { if(argc >= 2) { /* TEST 1 Standard */ if(!strcmp(argv[1], "STD")) { char *str = "No extra string provided"; char *file = NULL; if (argc >= 3) str = argv[2]; if (argc >= 4) file = argv[3]; SetNamePgm("test_liblog"); SetNameHost("localhost"); SetDefaultLogging("TEST"); InitLogging(); AddFamilyError(ERR_POSIX, "POSIX Errors", tab_systeme_status); LogTest("AddFamilyError = %d", AddFamilyError(ERR_DUMMY, "Family Dummy", tab_test_err)); LogTest("The family which was added is %s", ReturnNameFamilyError(ERR_DUMMY)); run_Tests(TRUE, "monothread", str, file); } /* TEST 1 multithread */ else if(!strcmp(argv[1], "MT")) { /* multithread test */ pthread_attr_t th_attr[NB_THREADS]; pthread_t threads[NB_THREADS]; int th_index, i; void *result; SetNamePgm("test_liblog"); SetNameHost("localhost"); SetDefaultLogging("STDOUT"); InitLogging(); AddFamilyError(ERR_POSIX, "POSIX Errors", tab_systeme_status); LogTest("AddFamilyError = %d", AddFamilyError(ERR_DUMMY, "Family Dummy", tab_test_err)); LogTest("The family which was added is %s", ReturnNameFamilyError(ERR_DUMMY)); /* creation of attributes */ for(th_index = 0; th_index < NB_THREADS; th_index++) { pthread_attr_init(&th_attr[th_index]); pthread_attr_setdetachstate(&th_attr[th_index], PTHREAD_CREATE_JOINABLE); } /* creation of threads with their names */ for(i = 0; i < NB_THREADS; i++) { int rc; char *thread_name = malloc(256); snprintf(thread_name, 256, "thread %3d", i); rc = pthread_create(&(threads[i]), &th_attr[i], run_MT_Tests, (void *)thread_name); } /* waiting for threads termination */ for(i = 0; i < NB_THREADS; i++) { pthread_join(threads[i], &result); if(result) return 1; } return 0; } /* unknown test */ else { fprintf(stderr, "%s", usage); exit(1); } } else { fprintf(stderr, "%s", usage); exit(1); } return 0; }
static int do_test (void) { int result = 0; char name[sizeof "/tst-mqueue6-" + sizeof (pid_t) * 3]; snprintf (name, sizeof (name), "/tst-mqueue6-%u", getpid ()); struct mq_attr attr = { .mq_maxmsg = 1, .mq_msgsize = 1 }; mqd_t q = mq_open (name, O_CREAT | O_EXCL | O_RDWR, 0600, &attr); if (q == (mqd_t) -1) { printf ("mq_open failed with: %m\n"); return result; } else add_temp_mq (name); pthread_attr_t nattr; if (pthread_attr_init (&nattr) || pthread_attr_setguardsize (&nattr, 0)) { puts ("pthread_attr_t setup failed"); result = 1; } fct_guardsize = 1; struct sigevent ev; memset (&ev, 0xaa, sizeof (ev)); ev.sigev_notify = SIGEV_THREAD; ev.sigev_notify_function = fct; ev.sigev_notify_attributes = &nattr; ev.sigev_value.sival_ptr = &q; if (mq_notify (q, &ev) != 0) { printf ("mq_notify (q, { SIGEV_THREAD }) failed with: %m\n"); result = 1; } size_t ps = sysconf (_SC_PAGESIZE); if (pthread_attr_setguardsize (&nattr, 32 * ps)) { puts ("pthread_attr_t setup failed"); result = 1; } if (mq_notify (q, &ev) == 0) { puts ("second mq_notify (q, { SIGEV_NONE }) unexpectedly succeeded"); result = 1; } else if (errno != EBUSY) { printf ("second mq_notify (q, { SIGEV_NONE }) failed with: %m\n"); result = 1; } if (fct_cnt != 0) { printf ("fct called too early (%d on %d)\n", fct_cnt, __LINE__); result = 1; } result |= mqsend (q); result |= mqrecv (q); result |= mqrecv (q); if (fct_cnt != 1) { printf ("fct not called (%d on %d)\n", fct_cnt, __LINE__); result = 1; } else if (fct_guardsize != 0) { printf ("fct_guardsize %zd != 0\n", fct_guardsize); result = 1; } if (mq_notify (q, &ev) != 0) { printf ("third mq_notify (q, { SIGEV_NONE }) failed with: %m\n"); result = 1; } if (mq_notify (q, NULL) != 0) { printf ("mq_notify (q, NULL) failed with: %m\n"); result = 1; } memset (&ev, 0x11, sizeof (ev)); ev.sigev_notify = SIGEV_THREAD; ev.sigev_notify_function = fct; ev.sigev_notify_attributes = &nattr; ev.sigev_value.sival_ptr = &q; if (mq_notify (q, &ev) != 0) { printf ("mq_notify (q, { SIGEV_THREAD }) failed with: %m\n"); result = 1; } if (pthread_attr_setguardsize (&nattr, 0)) { puts ("pthread_attr_t setup failed"); result = 1; } if (mq_notify (q, &ev) == 0) { puts ("second mq_notify (q, { SIGEV_NONE }) unexpectedly succeeded"); result = 1; } else if (errno != EBUSY) { printf ("second mq_notify (q, { SIGEV_NONE }) failed with: %m\n"); result = 1; } if (fct_cnt != 1) { printf ("fct called too early (%d on %d)\n", fct_cnt, __LINE__); result = 1; } result |= mqsend (q); result |= mqrecv (q); result |= mqrecv (q); if (fct_cnt != 2) { printf ("fct not called (%d on %d)\n", fct_cnt, __LINE__); result = 1; } else if (fct_guardsize != 32 * ps) { printf ("fct_guardsize %zd != %zd\n", fct_guardsize, 32 * ps); result = 1; } if (mq_notify (q, &ev) != 0) { printf ("third mq_notify (q, { SIGEV_NONE }) failed with: %m\n"); result = 1; } if (mq_notify (q, NULL) != 0) { printf ("mq_notify (q, NULL) failed with: %m\n"); result = 1; } if (pthread_attr_destroy (&nattr) != 0) { puts ("pthread_attr_destroy failed"); result = 1; } if (mq_unlink (name) != 0) { printf ("mq_unlink failed: %m\n"); result = 1; } if (mq_close (q) != 0) { printf ("mq_close failed: %m\n"); result = 1; } memset (&ev, 0x55, sizeof (ev)); ev.sigev_notify = SIGEV_THREAD; ev.sigev_notify_function = fct; ev.sigev_notify_attributes = NULL; ev.sigev_value.sival_int = 0; if (mq_notify (q, &ev) == 0) { puts ("mq_notify on closed mqd_t unexpectedly succeeded"); result = 1; } else if (errno != EBADF) { printf ("mq_notify on closed mqd_t did not fail with EBADF: %m\n"); result = 1; } if (fct_err) result = 1; return result; }
int main(int ac, char **av) { int ch, i=0; pid_t pid; FILE *fp; uid_t uid; #ifdef USE_THREAD pthread_t tid; pthread_attr_t attr; struct rlimit rl; rlim_t max_fd = (rlim_t)MAX_FD; rlim_t save_fd = 0; #endif #ifdef USE_THREAD threading = 1; max_thread = MAX_THREAD; #endif max_child = MAX_CHILD; cur_child = 0; /* create service socket table (malloc) */ if (serv_init(NULL) < 0) { msg_out(crit, "cannot malloc: %m"); exit(-1); } proxy_tbl = NULL; proxy_tbl_ind = 0; method_num = 0; uid = getuid(); openlog(ident, LOG_PID | LOG_NDELAY, SYSLOGFAC); while((ch = getopt(ac, av, "a:c:i:x:J:m:o:p:u:frstbwgIqvh?")) != -1) switch (ch) { case 'a': if (optarg != NULL) { for (i=0; i<sizeof method_tab; optarg++) { if (*optarg == '\0') break; switch (*optarg) { case 'p': if ( uid != 0 ) { /* process does not started by root */ msg_out(warn, "uid == %d (!=0)," "user/pass auth will not work, ignored.", uid); break; } method_tab[i++] = S5AUSRPAS; method_num++; break; case 'n': method_tab[i++] = S5ANOAUTH; method_num++; break; default: break; } } } break; case 'b': bind_restrict = 0; break; case 'c': if (optarg != NULL) { config = strdup(optarg); } break; case 'u': if (optarg != NULL) { pwdfile = strdup(optarg); } break; case 'i': if (optarg != NULL) { if (serv_init(optarg) < 0) { msg_out(warn, "cannot init server socket(-i %s): %m", optarg); break; } } break; #ifdef SO_BINDTODEVICE case 'J': if (optarg != NULL) { bindtodevice = strdup(optarg); } break; #endif case 'x': if (optarg != NULL) { bindout = strdup(optarg); } break; case 'o': if (optarg != NULL) { idle_timeout = atol(optarg); } break; case 'p': if (optarg != NULL) { pidfile = strdup(optarg); } break; case 'm': if (optarg != NULL) { #ifdef USE_THREAD max_thread = atoi(optarg); #endif max_child = atoi(optarg); } break; case 't': #ifdef USE_THREAD threading = 0; /* threading disabled. */ #endif break; case 'g': same_interface = 1; break; case 'f': fg = 1; break; case 'r': resolv_client = 1; break; case 's': forcesyslog = 1; break; case 'w': #ifdef HAVE_LIBWRAP use_tcpwrap = 1; #endif /* HAVE_LIBWRAP */ break; case 'I': inetd_mode = 1; break; case 'q': be_quiet = 1; break; case 'v': show_version(); exit(1); case 'h': case '?': default: usage(); } ac -= optind; av += optind; if (fg && !forcesyslog && isatty(fileno(stderr))) setvbuf(stderr, NULL, _IOLBF, 0); if ((fp = fopen(config, "r")) != NULL) { if (readconf(fp) != 0) { /* readconf error */ exit(1); } fclose(fp); } if (inetd_mode) { /* close all server socket if opened */ close_all_serv(); /* assuming that STDIN_FILENO handles bi-directional */ exit(inetd_service(STDIN_FILENO)); /* not reached */ } if (serv_sock_ind == 0) { /* no valid ifs yet */ if (serv_init(":") < 0) { /* use default */ /* fatal */ msg_out(crit, "cannot open server socket"); exit(1); } } #ifdef USE_THREAD if ( ! threading ) { #endif if (queue_init() != 0) { msg_out(crit, "cannot init signal queue"); exit(1); } #ifdef USE_THREAD } #endif /* try changing working directory */ if ( chdir(WORKDIR0) != 0 ) if ( chdir(WORKDIR1) != 0 ) msg_out(norm, "giving up chdir to workdir"); if (!fg) { /* force stdin/out/err allocate to /dev/null */ fclose(stdin); fp = fopen("/dev/null", "w+"); if (fileno(fp) != STDIN_FILENO) { msg_out(crit, "fopen: %m"); exit(1); } if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1) { msg_out(crit, "dup2-1: %m"); exit(1); } if (dup2(STDIN_FILENO, STDERR_FILENO) == -1) { msg_out(crit, "dup2-2: %m"); exit(1); } switch(fork()) { case -1: msg_out(crit, "fork: %m"); exit(1); case 0: /* child */ pid = setsid(); if (pid == -1) { msg_out(crit, "setsid: %m"); exit(1); } break; default: /* parent */ exit(0); } } master_pid = getpid(); umask(S_IWGRP|S_IWOTH); if ((fp = fopen(pidfile, "w")) != NULL) { fprintf(fp, "%u\n", (unsigned)master_pid); fchown(fileno(fp), PROCUID, PROCGID); fclose(fp); } else { msg_out(warn, "cannot open pidfile %s", pidfile); } setsignal(SIGHUP, reload); if (fg) setsignal(SIGINT, cleanup); else setsignal(SIGINT, SIG_IGN); setsignal(SIGQUIT, SIG_IGN); setsignal(SIGILL, SIG_IGN); setsignal(SIGTRAP, SIG_IGN); setsignal(SIGABRT, SIG_IGN); #ifdef SIGEMT setsignal(SIGEMT, SIG_IGN); #endif setsignal(SIGSYS, SIG_IGN); setsignal(SIGPIPE, SIG_IGN); setsignal(SIGALRM, SIG_IGN); setsignal(SIGTERM, cleanup); setsignal(SIGUSR1, SIG_IGN); setsignal(SIGUSR2, SIG_IGN); #ifdef SIGPOLL setsignal(SIGPOLL, SIG_IGN); #endif setsignal(SIGVTALRM, SIG_IGN); setsignal(SIGPROF, SIG_IGN); setsignal(SIGXCPU, SIG_IGN); setsignal(SIGXFSZ, SIG_IGN); #ifdef USE_THREAD if ( threading ) { if (max_thread <= 0 || max_thread > THREAD_LIMIT) { max_thread = THREAD_LIMIT; } /* resource limit is problem in threadig (e.g. Solaris:=64)*/ memset((caddr_t)&rl, 0, sizeof rl); if (getrlimit(RLIMIT_NOFILE, &rl) != 0) msg_out(warn, "getrlimit: %m"); else save_fd = rl.rlim_cur; if (rl.rlim_cur < (rlim_t)max_fd) rl.rlim_cur = max_fd; /* willing to fix to max_fd */ if ( rl.rlim_cur != save_fd ) /* if rlim_cur is changed */ if (setrlimit(RLIMIT_NOFILE, &rl) != 0) msg_out(warn, "cannot set rlimit(max_fd)"); setregid(0, PROCGID); setreuid(0, PROCUID); pthread_mutex_init(&mutex_select, NULL); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); msg_out(norm, "Starting: MAX_TH(%d)", max_thread); for (i=0; i<max_thread; i++) { if (pthread_create(&tid, &attr, (void *)&serv_loop, (void *)NULL) != 0) exit(1); } main_thread = pthread_self(); /* store main thread ID */ for (;;) { pause(); } } else { #endif setsignal(SIGCHLD, reapchild); setregid(0, PROCGID); setreuid(0, PROCUID); msg_out(norm, "Starting: MAX_CH(%d)", max_child); serv_loop(); #ifdef USE_THREAD } #endif return(0); }
static int reflowPage(lua_State *L) { DjvuPage *page = (DjvuPage*) luaL_checkudata(L, 1, "djvupage"); KOPTContext *kctx = (KOPTContext*) lua_topointer(L, 2); ddjvu_render_mode_t mode = (int) luaL_checkint(L, 3); ddjvu_rect_t prect; ddjvu_rect_t rrect; int px, py, pw, ph, rx, ry, rw, rh, status; px = 0; py = 0; pw = ddjvu_page_get_width(page->page_ref); ph = ddjvu_page_get_height(page->page_ref); prect.x = px; prect.y = py; rx = (int)kctx->bbox.x0; ry = (int)kctx->bbox.y0; rw = (int)(kctx->bbox.x1 - kctx->bbox.x0); rh = (int)(kctx->bbox.y1 - kctx->bbox.y0); double zoom = kctx->zoom*kctx->quality; float scale = ((2*zoom*kctx->dev_width) / (double)pw + \ (2*zoom*kctx->dev_height) / (double)ph) / 2; prect.w = pw * scale; prect.h = ph * scale; rrect.x = rx * scale; rrect.y = ry * scale; rrect.w = rw * scale; rrect.h = rh * scale; printf("rendering page:%d,%d,%d,%d\n",rrect.x,rrect.y,rrect.w,rrect.h); kctx->zoom = scale; WILLUSBITMAP *src = &kctx->src; bmp_init(src); src->width = rrect.w; src->height = rrect.h; src->bpp = 8; bmp_alloc(src); if (src->bpp == 8) { int ii; for (ii = 0; ii < 256; ii++) src->red[ii] = src->blue[ii] = src->green[ii] = ii; } ddjvu_format_set_row_order(page->doc->pixelformat, 1); status = ddjvu_page_render(page->page_ref, mode, &prect, &rrect, page->doc->pixelformat, bmp_bytewidth(src), (char *) src->data); if (kctx->precache) { pthread_t rf_thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&rf_thread, &attr, k2pdfopt_reflow_bmp, (void*) kctx); pthread_attr_destroy(&attr); } else { k2pdfopt_reflow_bmp(kctx); } return 0; }
int main(int argc, char *argv[]) { int s, tnum, opt, num_threads; struct thread_info *tinfo; pthread_attr_t attr; int stack_size; void *res; /* The "-s" option specifies a stack size for our threads */ stack_size = -1; while ((opt = getopt(argc, argv, "s:")) != -1) { switch (opt) { case 's': stack_size = strtoul(optarg, NULL, 0); break; default: fprintf(stderr, "Usage: %s [-s stack-size] arg...\n", argv[0]); exit(EXIT_FAILURE); } } num_threads = argc - optind; printf("argc %d: optind %d num_threads = %d\n", argc, optind, num_threads); /* Initialize thread creation attributes */ s = pthread_attr_init(&attr); if (s != 0) handle_error_en(s, "pthread_attr_init"); if (stack_size > 0) { s = pthread_attr_setstacksize(&attr, stack_size); if (s != 0) handle_error_en(s, "pthread_attr_setstacksize"); } /* Allocate memory for pthread_create() arguments */ tinfo = calloc(num_threads, sizeof(struct thread_info)); if (tinfo == NULL) handle_error("calloc"); /* Create one thread for each command-line argument */ for (tnum = 0; tnum < num_threads; tnum++) { tinfo[tnum].thread_num = tnum + 1; tinfo[tnum].argv_string = argv[optind + tnum]; /* The pthread_create() call stores the thread ID into corresponding element of tinfo[] */ s = pthread_create(&tinfo[tnum].thread_id, &attr, &thread_start, &tinfo[tnum]); if (s != 0) handle_error_en(s, "pthread_create"); } /* Destroy the thread attributes object, since it is no longer needed */ s = pthread_attr_destroy(&attr); if (s != 0) handle_error_en(s, "pthread_attr_destroy"); /* Now join with each thread, and display its returned value */ for (tnum = 0; tnum < num_threads; tnum++) { s = pthread_join(tinfo[tnum].thread_id, &res); if (s != 0) handle_error_en(s, "pthread_join"); printf("Joined with thread %d; returned value was %s\n", tinfo[tnum].thread_num, (char *) res); free(res); /* Free memory allocated by thread */ } printf("Extining from main thread\n"); free(tinfo); exit(EXIT_SUCCESS); }
/*static*/ int alsa_init(cubeb ** context, char const * context_name) { (void)context_name; cubeb * ctx; int r; int i; int fd[2]; pthread_attr_t attr; snd_pcm_t * dummy; assert(context); *context = NULL; pthread_mutex_lock(&cubeb_alsa_mutex); if (!cubeb_alsa_error_handler_set) { snd_lib_error_set_handler(silent_error_handler); cubeb_alsa_error_handler_set = 1; } pthread_mutex_unlock(&cubeb_alsa_mutex); ctx = calloc(1, sizeof(*ctx)); assert(ctx); ctx->ops = &alsa_ops; r = pthread_mutex_init(&ctx->mutex, NULL); assert(r == 0); r = pipe(fd); assert(r == 0); for (i = 0; i < 2; ++i) { fcntl(fd[i], F_SETFD, fcntl(fd[i], F_GETFD) | FD_CLOEXEC); fcntl(fd[i], F_SETFL, fcntl(fd[i], F_GETFL) | O_NONBLOCK); } ctx->control_fd_read = fd[0]; ctx->control_fd_write = fd[1]; /* Force an early rebuild when alsa_run is first called to ensure fds and nfds have been initialized. */ ctx->rebuild = 1; r = pthread_attr_init(&attr); assert(r == 0); r = pthread_attr_setstacksize(&attr, 256 * 1024); assert(r == 0); r = pthread_create(&ctx->thread, &attr, alsa_run_thread, ctx); assert(r == 0); r = pthread_attr_destroy(&attr); assert(r == 0); /* Open a dummy PCM to force the configuration space to be evaluated so that init_local_config_with_workaround can find and modify the default node. */ r = alsa_locked_pcm_open(&dummy, SND_PCM_STREAM_PLAYBACK, NULL); if (r >= 0) { alsa_locked_pcm_close(dummy); } ctx->is_pa = 0; pthread_mutex_lock(&cubeb_alsa_mutex); ctx->local_config = init_local_config_with_workaround(CUBEB_ALSA_PCM_NAME); pthread_mutex_unlock(&cubeb_alsa_mutex); if (ctx->local_config) { ctx->is_pa = 1; r = alsa_locked_pcm_open(&dummy, SND_PCM_STREAM_PLAYBACK, ctx->local_config); /* If we got a local_config, we found a PA PCM. If opening a PCM with that config fails with EINVAL, the PA PCM is too old for this workaround. */ if (r == -EINVAL) { pthread_mutex_lock(&cubeb_alsa_mutex); snd_config_delete(ctx->local_config); pthread_mutex_unlock(&cubeb_alsa_mutex); ctx->local_config = NULL; } else if (r >= 0) { alsa_locked_pcm_close(dummy); } } *context = ctx; return CUBEB_OK; }
void cthd_rapl_power_meter::rapl_enable_periodic_timer() { pthread_attr_init(&thd_attr); pthread_attr_setdetachstate(&thd_attr, PTHREAD_CREATE_DETACHED); pthread_create(&poll_thread, &thd_attr, rapl_periodic_callback, (void*) this); }
//read me:?????ϱ?ͨ?À±???È¥??È¡???Õ£???Ò»????buf(2048byte),??buf????????ϵͳ???ì³£?? int main(int argc ,char** argv) { char infoData[2048] = {0}; char cmdStr[CMD_LEN_MAX] = {0}; pthread_attr_t attr; int count = 3; DEMO_PRINT("Entry AmoiTest\r\n"); pthread_mutex_init(&SetCmdMutex,NULL); pthread_mutex_init(&GetCmdMutex,NULL); //sim0 ?????ϱ?ͨ?? sFdSim0_0 = open ("/dev/CHNPTYL0", O_RDWR); if(sFdSim0_0 <=0) { DEMO_PRINT("system broken ,exit\n"); exit(-1); } /* //cmux init strcpy(cmdStr, "AT+SMMSWAP=0\r"); send_atcmd(sFdSim0_0, cmdStr); strcpy(cmdStr, "AT+CMUX=0\r"); send_atcmd(sFdSim0_0, cmdStr); */ //sim0 atͨ?? ??Ϊat????????ͨ?? sFdSim0_1 = open ("/dev/CHNPTYL1", O_RDWR); if( sFdSim0_1 <= 0) { DEMO_PRINT("open /dev/CHNPTYL1 error\r\n"); exit(-1); } //sim0 atͨ?? ??Ϊat??ѯ????ͨ?? sFdSim0_2 = open ("/dev/CHNPTYL2", O_RDWR); if( sFdSim0_2 <= 0) { DEMO_PRINT("open /dev/CHNPTYL2 error\r\n"); exit(-1); } pthread_attr_init (&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&sRcvThreadSim0, &attr, reportAnalysisHandleSim0, NULL); if (argc == 2 && argv[1][0] == 'x') { printf("begin stop\n"); strcpy(cmdStr, "AT+CGACT=0\r"); GeneralCommand(cmdStr,2); system("ip addr flush dev seth_lte0 "); return 0; } /* //??ʼ?????? strcpy(cmdStr, "ATE0Q0V1\r"); GeneralCommand(cmdStr,2); strcpy(cmdStr, "AT+CCED=2,8\r"); GeneralCommand(cmdStr,2); strcpy(cmdStr, "AT+CREG=0\r"); GeneralCommand(cmdStr,5); strcpy(cmdStr, "AT+CEREG=1\r"); GeneralCommand(cmdStr,5); strcpy(cmdStr, "AT+CEMODE=1\r"); GeneralCommand(cmdStr,2); */ /* strcpy(cmdStr, "AT+SPSWITCHDATACARD=1,0"); GeneralCommand(cmdStr,10); strcpy(cmdStr, "ATS0=1"); GeneralCommand(cmdStr,10); */ strcpy(cmdStr, "AT+SFUN=5\r"); GeneralCommand(cmdStr,50); strcpy(cmdStr, "AT+SPTESTMODEM=1,254\r"); GeneralCommand(cmdStr,2); strcpy(cmdStr, "AT+SFUN=4\r"); GeneralCommand(cmdStr,50); //??ѯcereg ×¢???Ϻ???Ö´?в??? GET_CEREG_STATE: sleep(2); strcpy(cmdStr, "AT+CEREG?\r"); memset(infoData,0,2048); infoGetCommand(cmdStr,5,infoData,2048); if(strstr(infoData, "+CEREG: 2,1") ==0) { if (--count) { goto GET_CEREG_STATE; } else { printf("card not registerd\n"); return -1; } } strcpy(cmdStr, "AT+CGDCONT=1,\"ip\",\"cmnet\"\r"); GeneralCommand(cmdStr,5); strcpy(cmdStr, "AT+CGPCO=0,\"name\",\"password\",1,1\r"); GeneralCommand(cmdStr,5); strcpy(cmdStr, "AT+CGEQREQ=1,2,0,0,0,0,2,0,\"1e4\",\"0e0\",3,0,0\r"); GeneralCommand(cmdStr,5); strcpy(cmdStr, "AT+SPREATTACH\r"); GeneralCommand(cmdStr,120); sleep(2); strcpy(cmdStr, "AT+CGDATA=\"M-ETHER\",1\r"); GeneralCommand(cmdStr,120); strcpy(cmdStr, "AT+CGCONTRDP=1\r"); memset(infoData,0,2048); infoGetCommand(cmdStr,10,infoData,2048); printf("%s",infoData); /* while(1) { pause(); } */ return 0; }
void semtimed_test(void) { pthread_t poster_thread = (pthread_t)0; #ifdef SDCC pthread_addr_t result; #endif struct sched_param sparam; struct timespec abstime; struct timespec before; struct timespec after; int prio_min; int prio_max; int prio_mid; pthread_attr_t attr; int status; printf("semtimed_test: Initializing semaphore to 0\n"); sem_init(&sem, 0, 0); /* First, make sure that the timeout expires if the semaphore is never posted */ (void)clock_gettime(CLOCK_REALTIME, &before); abstime.tv_sec = before.tv_sec + 2; abstime.tv_nsec = before.tv_nsec; printf("semtimed_test: Waiting for two second timeout\n"); status = sem_timedwait(&sem, &abstime); (void)clock_gettime(CLOCK_REALTIME, &after); if (status == OK) { printf("semtimed_test: ERROR: sem_timedwait succeeded\n"); } else { int errcode = errno; if (errcode == ETIMEDOUT) { printf("samwait_test: PASS\n"); } else { printf("semtimed_test: ERROR: sem_timedwait failed with: %d\n", errcode); } } (void)clock_gettime(CLOCK_REALTIME, &after); printf("BEFORE: (%lu sec, %lu nsec)\n", (unsigned long)before.tv_sec, (unsigned long)before.tv_nsec); printf("AFTER: (%lu sec, %lu nsec)\n", (unsigned long)after.tv_sec, (unsigned long)after.tv_nsec); /* Now make sure that the time wait returns successfully if the semaphore is posted */ /* Start a poster thread. It will wait 1 seconds and post the semaphore */ printf("semtimed_test: Starting poster thread\n"); status = pthread_attr_init(&attr); if (status != OK) { printf("semtimed_test: ERROR: pthread_attr_init failed, status=%d\n", status); } prio_min = sched_get_priority_min(SCHED_FIFO); prio_max = sched_get_priority_max(SCHED_FIFO); prio_mid = (prio_min + prio_max) / 2; sparam.sched_priority = (prio_mid + prio_max) / 2; status = pthread_attr_setschedparam(&attr, &sparam); if (status != OK) { printf("semtimed_test: ERROR: pthread_attr_setschedparam failed, status=%d\n", status); } else { printf("semtimed_test: Set thread 1 priority to %d\n", sparam.sched_priority); } printf("semtimed_test: Starting poster thread 3\n"); status = pthread_attr_init(&attr); if (status != 0) { printf("semtimed_test: ERROR: pthread_attr_init failed, status=%d\n", status); } sparam.sched_priority = (prio_min + prio_mid) / 2; status = pthread_attr_setschedparam(&attr, &sparam); if (status != OK) { printf("semtimed_test: pthread_attr_setschedparam failed, status=%d\n", status); } else { printf("semtimed_test: Set thread 3 priority to %d\n", sparam.sched_priority); } status = pthread_create(&poster_thread, &attr, poster_func, NULL); if (status != 0) { printf("semtimed_test: ERROR: Poster thread creation failed: %d\n", status); sem_destroy(&sem); return; } /* Up to two seconds for the semaphore to be posted */ (void)clock_gettime(CLOCK_REALTIME, &before); abstime.tv_sec = before.tv_sec + 2; abstime.tv_nsec = before.tv_nsec; printf("semtimed_test: Waiting for two second timeout\n"); status = sem_timedwait(&sem, &abstime); (void)clock_gettime(CLOCK_REALTIME, &after); if (status < 0) { int errcode = errno; printf("semtimed_test: ERROR: sem_timedwait failed with: %d\n", errcode); } else { printf("semtimed_test: PASS: sem_timedwait succeeded\n"); } (void)clock_gettime(CLOCK_REALTIME, &after); printf("BEFORE: (%lu sec, %lu nsec)\n", (unsigned long)before.tv_sec, (unsigned long)before.tv_nsec); printf("AFTER: (%lu sec, %lu nsec)\n", (unsigned long)after.tv_sec, (unsigned long)after.tv_nsec); /* Clean up detritus left by the pthread */ #ifdef SDCC if (poster_thread != (pthread_t)0) { pthread_join(poster_thread, &result); } #else if (poster_thread != (pthread_t)0) { pthread_join(poster_thread, NULL); } #endif sem_destroy(&sem); }
int main(int argc, char* argv[]) { // Variable declarations int i, port, sd_current, addrlen, handlingMethod, fifo, setval, max_fd; struct sockaddr_in sin, pin; configuration config; char error[1024]; pthread_t handler; pthread_attr_t att; pid_t pid; fd_set rfds; // Set execution to true execute = true; // Clear file creation mask. umask(0); // Set default handling method to thread handlingMethod = _THREAD; // Get size of pin .. addrlen = sizeof(pin); // Signal handlers signal(SIGPIPE, SIG_IGN); signal(SIGINT, sig_handle_int); signal(SIGABRT, sig_handle_int); // Set default config setDefaultConfig(&config); // Set root dir to current running directory path_init(&config); rootDir(argv[0]); // Parse config file if (parseConfig(&config) == -1) { exit(-1); } // Check arguments if(argc > 1) { for(i = 1; i < argc; i++) { switch(argv[i][1]) { // Help case 'h': printHelp(); return 3; break; // Port case 'p': i++; if(i >= argc) { printHelp(); return 3; } if(argv[i][0] != '-') { if((port = atoi(argv[i])) != 0 && port < 65536) { config.listenPort = port; printf("Port number: %d\n", port); } else { printHelp(); return 3; } } else { printHelp(); return 3; } break; // Deamonize case 'd': // Start daemon if set printf("Starting daemon...\n"); daemonfunc(); break; // Log file case 'l': i++; if(i >= argc) { printHelp(); return 3; } if(argv[i][0] != '-') { strncpy(config.accLogPath, argv[i], sizeof(config.accLogPath)); } else { printHelp(); return 3; } break; // Mode of operation case 's': i++; if(i >= argc) { printHelp(); return 3; } if(strncmp(argv[i], "thread", 6) == 0) handlingMethod = _THREAD; else if(strncmp(argv[i], "fork", 4) == 0) handlingMethod = _FORK; else { printHelp(); return 3; } break; case 'c': i++; if(i >= argc) { printHelp(); return 3; } if(argv[i][0] != '-') { strncpy(config.configPath, argv[i], sizeof(config.configPath)); } else { printHelp(); return 3; } break; } } } // Init logfunctions if (log_init(&config) == -1) { exit(-1); } // Create fifo if prefork is set if (handlingMethod == _FORK) { // Create the named fifo pipe mkfifo(config.fifoPath, 0666); // Try opening the pipe if((fifo = open(config.fifoPath, O_RDWR)) == -1) { sprintf(error, "Unable to open FIFO-pipe, %s", strerror(errno)); log_server(LOG_CRIT, error); execute = false; // Terminate } } // Check super user if (getuid() != 0) { perror("You have to be root to run this program"); exit(-1); } // Set root directory to document root chdir(config.basedir); if (chroot(config.basedir) == -1) { sprintf(error, "Unable to change root directory, %s", strerror(errno)); log_server(LOG_ERR, error); execute = false; // Terminate } // Drop root privileges if (setgid(getgid()) == -1) { sprintf(error, "Unable to change user, %s", strerror(errno)); log_server(LOG_ERR, error); execute = false; // Terminate } if (setuid(getuid()) == -1) { sprintf(error, "Unable to change user, %s", strerror(errno)); log_server(LOG_ERR, error); execute = false; // Terminate } // Create listening socket // Domain -> AF_INET = IPV4 // Type -> SOCK_STREAM = TCP if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { sprintf(error, "Unable to open socket, %s", strerror(errno)); log_server(LOG_ERR, error); execute = false; // Terminate } // Zeroize sin memset(&sin, 0, sizeof(sin)); // Set domain sin.sin_family = AF_INET; // Set any in address sin.sin_addr.s_addr = INADDR_ANY; // Set port, hton converts byteorder sin.sin_port = htons(config.listenPort); // Try binding the socket if(bind(sd, (struct sockaddr*) &sin, sizeof(sin)) == -1) { sprintf(error, "Unable to bind socket, %s", strerror(errno)); log_server(LOG_ERR, error); execute = false; // Terminate } // Start to listen for requests if(listen(sd, config.backlog) == -1) { sprintf(error, "Too loud unable to listen, %s", strerror(errno)); log_server(LOG_ERR, error); execute = false; // Terminate } // Init thread lock pthread_mutex_init(&thread_lock, NULL); // If handling method is set to thread if(handlingMethod == _THREAD) { // Init thread attr pthread_attr_init(&att); // Set threads to detached state pthread_attr_setdetachstate(&att, PTHREAD_CREATE_DETACHED); // Set system scope pthread_attr_setscope(&att, PTHREAD_SCOPE_SYSTEM); // Set RoundRobin scheduling pthread_attr_setschedpolicy(&att, SCHED_RR); // Not supported in LINUX pthreads // Start accepting requests while(execute) { // Accept a request from queue, blocking if ((sd_current = accept(sd, (struct sockaddr*) &pin, (socklen_t*) &addrlen)) == -1) { if (execute) { sprintf(error, "Unable to accept request, %s", strerror(errno)); log_server(LOG_ERR, error); } close(sd_current); execute = false; // Terminate } else { // Shit happens, if server is out of memory just skip the request _rqhd_args *args = malloc(sizeof(_rqhd_args)); if (args == NULL) { sprintf(error, "Unable to allocate memory, %s", strerror(errno)); log_server(LOG_CRIT, error); close(sd_current); } else { // Set arguments args->sd = sd_current; args->pin = pin; args->config = &config; } // Create thread if(pthread_create(&handler, &att, requestHandle, args) != 0) { sprintf(error, "Unable to start thread, %s", strerror(errno)); log_server(LOG_CRIT, error); close(sd_current); execute = false; // Terminate } } } // Destroy attributes pthread_attr_destroy(&att); } // Else if handling method is set to fork else if(handlingMethod == _FORK) { max_fd = sd; if (fifo > sd) max_fd = fifo; // Start accepting requests while(execute) { FD_ZERO(&rfds); FD_SET(sd, &rfds); FD_SET(fifo, &rfds); // Accept request or handle child setval = select(max_fd + 1, &rfds, NULL, NULL, NULL); if (FD_ISSET(sd, &rfds)) { // Accept a request from queue if ((sd_current = accept(sd, (struct sockaddr*) &pin, (socklen_t*) &addrlen)) == -1) { if (execute) { sprintf(error, "Unable to accept request, %s", strerror(errno)); log_server(LOG_ERR, error); } close(sd_current); execute = false; // Terminate } else { // Fork if((pid = fork()) == 0) { // CHILD ---------------------------------------------------- // Shit happens, if server is out of memory just skip the request _rqhd_args *args = malloc(sizeof(_rqhd_args)); if (args == NULL) { sprintf(error, "Unable to allocate memory, %s", strerror(errno)); log_server(LOG_CRIT, error); close(sd_current); } else { // Set arguments args->sd = sd_current; args->pin = pin; args->config = &config; // Call request handler requestHandle(args); } // Tell parent I'm done pid_t id = getpid(); if (write(fifo, &id, sizeof(pid_t)) == -1) { sprintf(error, "Unable to send pid, %s", strerror(errno)); log_server(LOG_ERR, error); } // Done execute = false; } else if(pid > 0) { // PARENT --------------------------------------------------- // Parent don't handle dirty work close(sd_current); } else { sprintf(error, "Unable to fork, %s", strerror(errno)); log_server(LOG_CRIT, error); close(sd_current); execute = false; // Terminate } } } else if (FD_ISSET(fifo, &rfds)) { // Get child pid from fifo and wait for it pid_t child; if (read(fifo, &child, sizeof(pid_t)) == -1) { sprintf(error, "Unable to read pid, %s", strerror(errno)); log_server(LOG_ERR, error); } waitpid(child, NULL, 0); } else if (setval == -1){ // Error sprintf(error, "Select failed or was interrupted, %s", strerror(errno)); log_server(LOG_ERR, error); execute = false; // Terminate } } // Close fifo close(fifo); } // Else not a valid handling method else { sprintf(error, "Invalid handling method is set"); log_server(LOG_ERR, error); } // Clean up pthread_mutex_destroy(&thread_lock); close(sd); log_destroy(); if (pid != 0) printf("Cleanup complete, no one will know I was here.\n"); return 0; }