static uintptr_t load_ppp_module() { if (module_dl_handler) { // already loaded return 0; } // allocate auxiliary instance if (!aux_instance) { aux_instance = calloc(1, sizeof(*aux_instance)); if (!aux_instance) return 1; aux_instance->id = tables_generate_new_pp_instance_id(); tables_add_pp_instance(aux_instance->id, aux_instance); } // allocate message loop for browser thread if (ppb_message_loop_get_current() == 0) { PP_Resource message_loop = ppb_message_loop_create(aux_instance->id); ppb_message_loop_attach_to_current_thread(message_loop); ppb_message_loop_proclaim_this_thread_browser(); } // allocate message loop for plugin thread (main thread) if (ppb_message_loop_get_for_main_thread() == 0) { pthread_barrier_init(&aux_instance->main_thread_barrier, NULL, 2); pthread_create(&aux_instance->main_thread, NULL, fresh_wrapper_main_thread, aux_instance); pthread_detach(aux_instance->main_thread); pthread_barrier_wait(&aux_instance->main_thread_barrier); pthread_barrier_destroy(&aux_instance->main_thread_barrier); } fpp_config_initialize(); if (tried_files) { g_list_free_full(tried_files, g_free); tried_files = NULL; } if (fpp_config_get_plugin_path()) { const char *ptr = fpp_config_get_plugin_path(); const char *last = strchr(ptr, ':'); uintptr_t ret; // parse ':'-separated list while (last != NULL) { // try entries one by one char *entry = strndup(ptr, last - ptr); ret = do_load_ppp_module(entry); free(entry); if (ret == 0) return 0; ptr = last + 1; last = strchr(ptr, ':'); } // and the last entry ret = do_load_ppp_module(ptr); if (ret == 0) return 0; goto failure; } // try all paths const char **path_list = fpp_config_get_plugin_path_list(); while (*path_list) { gchar *fname = g_strdup_printf("%s/%s", *path_list, fpp_config_get_plugin_file_name()); uintptr_t ret = do_load_ppp_module(fname); g_free(fname); if (ret == 0) return 0; path_list ++; } failure: config.quirks.plugin_missing = 1; use_fallback_version_strings(); trace_error("%s, can't find %s\n", __func__, fpp_config_get_plugin_file_name()); return 1; }
/* xdd_barrier() - This is the actual barrier subroutine. * The caller will block in this subroutine until all required threads enter * this subroutine <barrier> at which time they will all be released. * * The "owner" parameter indicates whether or not the calling thread is the * owner of this barrier. 0==NOT owner, 1==owner. If this thread owns this * barrier then it will be responsible for removing the "occupant" chain * upon being released from this barrier. * * Before entering the barrier, the occupant structure is added to the end * of the occupant chain. This allows the debug routine to see which threads * are in a barrier at any given time as well as when they entered the barrier. * * If the barrier is a Target Thread or a Worker Thread then the Target_Data pointer is * valid and the "current_barrier" member of that Target_Data is set to the barrier * pointer of the barrier that this thread is about to enter. Upon leaving the * barrier, this pointer is cleared. * * THIS SUBROUTINE IMPLEMENTS BARRIERS USING PTHREAD_BARRIERS */ int32_t xdd_barrier(struct xdd_barrier *bp, xdd_occupant_t *occupantp, char owner) { int32_t status; // Status of the pthread_barrier call /* "threads" is the number of participating threads */ if (bp->threads == 1) return(0); /* If there is only one thread then why bother sleeping */ // Put this Target_Data on the Barrier Target_Data Chain so that we can track it later if we need to /////// this is to keep track of which Target_Data are in a particular barrier at any given time... pthread_mutex_lock(&bp->mutex); // Add occupant structure here if (bp->counter == 0) { // Add first occupant to the chain bp->first_occupant = occupantp; bp->last_occupant = occupantp; occupantp->prev_occupant = occupantp; occupantp->next_occupant = occupantp; } else { // Add this barrier to the end of the chain occupantp->next_occupant = bp->first_occupant; // The last one on the chain points back to the first barrier on the chain as its "next" occupantp->prev_occupant = bp->last_occupant; bp->last_occupant->next_occupant = occupantp; bp->last_occupant = occupantp; } // Done adding this barrier to the chain if (occupantp->occupant_type & XDD_OCCUPANT_TYPE_TARGET ) { // Put the barrier pointer into this thread's Target_Data->current_barrier ((target_data_t *)(occupantp->occupant_data))->td_current_state |= TARGET_CURRENT_STATE_BARRIER; ((target_data_t *)(occupantp->occupant_data))->td_current_barrier = bp; } else if (occupantp->occupant_type & XDD_OCCUPANT_TYPE_WORKER_THREAD) { // Put the barrier pointer into this thread's Worker_Data->current_barrier ((worker_data_t *)(occupantp->occupant_data))->wd_current_state |= WORKER_CURRENT_STATE_BARRIER; ((worker_data_t *)(occupantp->occupant_data))->wd_current_barrier = bp; } bp->counter++; pthread_mutex_unlock(&bp->mutex); // Now we wait here at this barrier until all the other threads arrive... nclk_now(&occupantp->entry_time); #ifdef HAVE_PTHREAD_BARRIER_T status = pthread_barrier_wait(&bp->pbar); nclk_now(&occupantp->exit_time); if ((status != 0) && (status != PTHREAD_BARRIER_SERIAL_THREAD)) { fprintf(xgp->errout,"%s: xdd_barrier<pthread_barriers>: ERROR: pthread_barrier_wait failed: Barrier %s, status is %d, errno is %d\n", xgp->progname, bp->name, status, errno); perror("Reason"); status = -1; } #else status = xint_barrier_wait(&bp->pbar); nclk_now(&occupantp->exit_time); if (status != 0) { fprintf(xgp->errout,"%s: xdd_barrier<pthread_barriers>: ERROR: xint_barrier_wait failed: Barrier %s, status is %d, errno is %d\n", xgp->progname, bp->name, status, errno); perror("Reason"); status = -1; } #endif if (occupantp->occupant_type & XDD_OCCUPANT_TYPE_TARGET ) { // Clear this thread's Target_Data->current_barrier ((target_data_t *)(occupantp->occupant_data))->td_current_barrier = NULL; ((target_data_t *)(occupantp->occupant_data))->td_current_state &= ~TARGET_CURRENT_STATE_BARRIER; } else if (occupantp->occupant_type & XDD_OCCUPANT_TYPE_WORKER_THREAD) { // Put the barrier pointer into this thread's Worker_Data->current_barrier ((worker_data_t *)(occupantp->occupant_data))->wd_current_barrier = NULL; ((worker_data_t *)(occupantp->occupant_data))->wd_current_state &= ~WORKER_CURRENT_STATE_BARRIER; } // Clear this occupant chain if we are the owner of this barrier if (owner) { pthread_mutex_lock(&bp->mutex); // Clear the first/last chain pointers bp->first_occupant = NULL; bp->last_occupant = NULL; bp->counter = 0; pthread_mutex_unlock(&bp->mutex); } return(status); } // End of xdd_barrier() POSIX
hid_device * HID_API_EXPORT hid_open_path(const char *path) { hid_device *dev = NULL; libusb_device **devs; libusb_device *usb_dev; int res; int d = 0; int good_open = 0; dev = new_hid_device(); if(hid_init() < 0) return NULL; libusb_get_device_list(usb_context, &devs); while ((usb_dev = devs[d++]) != NULL) { struct libusb_device_descriptor desc; struct libusb_config_descriptor *conf_desc = NULL; int i,j,k; libusb_get_device_descriptor(usb_dev, &desc); if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0) continue; for (j = 0; j < conf_desc->bNumInterfaces; j++) { const struct libusb_interface *intf = &conf_desc->interface[j]; for (k = 0; k < intf->num_altsetting; k++) { const struct libusb_interface_descriptor *intf_desc; intf_desc = &intf->altsetting[k]; if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) { char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber); if (!strcmp(dev_path, path)) { /* Matched Paths. Open this device */ /* OPEN HERE */ res = libusb_open(usb_dev, &dev->device_handle); if (res < 0) { LOG("can't open device\n"); free(dev_path); break; } good_open = 1; #ifdef DETACH_KERNEL_DRIVER /* Detach the kernel driver, but only if the device is managed by the kernel */ if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) { res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber); if (res < 0) { libusb_close(dev->device_handle); LOG("Unable to detach Kernel Driver\n"); free(dev_path); good_open = 0; break; } } #endif res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber); if (res < 0) { LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res); free(dev_path); libusb_close(dev->device_handle); good_open = 0; break; } /* Store off the string descriptor indexes */ dev->manufacturer_index = desc.iManufacturer; dev->product_index = desc.iProduct; dev->serial_index = desc.iSerialNumber; /* Store off the interface number */ dev->interface = intf_desc->bInterfaceNumber; /* Find the INPUT and OUTPUT endpoints. An OUTPUT endpoint is not required. */ for (i = 0; i < intf_desc->bNumEndpoints; i++) { const struct libusb_endpoint_descriptor *ep = &intf_desc->endpoint[i]; /* Determine the type and direction of this endpoint. */ int is_interrupt = (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == LIBUSB_TRANSFER_TYPE_INTERRUPT; int is_output = (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT; int is_input = (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN; /* Decide whether to use it for intput or output. */ if (dev->input_endpoint == 0 && is_interrupt && is_input) { /* Use this endpoint for INPUT */ dev->input_endpoint = ep->bEndpointAddress; dev->input_ep_max_packet_size = ep->wMaxPacketSize; } if (dev->output_endpoint == 0 && is_interrupt && is_output) { /* Use this endpoint for OUTPUT */ dev->output_endpoint = ep->bEndpointAddress; } } pthread_create(&dev->thread, NULL, read_thread, dev); /* Wait here for the read thread to be initialized. */ pthread_barrier_wait(&dev->barrier); } free(dev_path); } } } libusb_free_config_descriptor(conf_desc); } libusb_free_device_list(devs, 1); /* If we have a good handle, return it. */ if (good_open) { return dev; } else { /* Unable to open any devices. */ free_hid_device(dev); return NULL; } }
void *MavlinkStatusTask(void *ptr) { MavlinkStruct *Mavlink = (MavlinkStruct *) ptr; AttitudeData *AttitudeDesire = Control.AttitudeDesire; AttitudeData *AttitudeMesure = Mavlink->AttitudeMesure; AttData Data, Speed; AttData DataD, SpeedD; AttData DataM, SpeedM; double Error[4] = {0.0, 0.0, 0.0, 0.0}; uint32_t TimeStamp; mavlink_message_t msg; uint16_t len; uint8_t buf[BUFFER_LENGTH]; int bytes_sent; uint32_t sensor = 0xf00f; printf("%s : Mavlink Status démarré\n", __FUNCTION__); pthread_barrier_wait(&(MavlinkStartBarrier)); while (MavlinkActivated) { sem_wait(&MavlinkStatusTimerSem); if (MavlinkActivated == 0) break; memset(buf, 0, BUFFER_LENGTH); pthread_spin_lock(&(AttitudeMesure->AttitudeLock)); memcpy((void *) &Data, (void *) &(AttitudeMesure->Data), sizeof(AttData)); memcpy((void *) &Speed, (void *) &(AttitudeMesure->Speed), sizeof(AttData)); TimeStamp = AttitudeMesure->timestamp_s*1000 + AttitudeMesure->timestamp_n/1000000L; pthread_spin_unlock(&(AttitudeMesure->AttitudeLock)); //Send Heartbeat mavlink_msg_heartbeat_pack(SYSTEM_ID, COMPONENT_ID, &msg, MAV_TYPE_HELICOPTER, MAV_AUTOPILOT_GENERIC, MAV_MODE_GUIDED_ARMED, 0, MAV_STATE_ACTIVE); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof(struct sockaddr_in)); // Send Status mavlink_msg_sys_status_pack(SYSTEM_ID, COMPONENT_ID, &msg, sensor, sensor, 0, 500, 11000, -1, -1, 0, 0, 0, 0, 0, 0); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof (struct sockaddr_in)); // Send Local Position mavlink_msg_local_position_ned_pack(SYSTEM_ID, COMPONENT_ID, &msg, TimeStamp, 0, 0, (float) Data.Elevation, 0, 0, (float) Speed.Elevation); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof(struct sockaddr_in)); pthread_spin_lock(&(AttitudeDesire->AttitudeLock)); memcpy((void *) &DataD, (void *) &(AttitudeDesire->Data), sizeof(AttData)); memcpy((void *) &SpeedD, (void *) &(AttitudeDesire->Speed), sizeof(AttData)); pthread_spin_unlock(&(AttitudeDesire->AttitudeLock)); pthread_spin_lock(&(AttitudeMesure->AttitudeLock)); memcpy((void *) &DataM, (void *) &(AttitudeMesure->Data), sizeof(AttData)); memcpy((void *) &SpeedM, (void *) &(AttitudeMesure->Speed), sizeof(AttData)); pthread_spin_unlock(&(AttitudeMesure->AttitudeLock)); Error[HEIGHT] = DataD.Elevation - DataM.Elevation; Error[ROLL] = DataD.Roll - DataM.Roll; Error[PITCH] = DataD.Pitch - DataM.Pitch; Error[YAW] = DataD.Yaw - DataM.Yaw; // Send Attitude mavlink_msg_attitude_pack(SYSTEM_ID, COMPONENT_ID, &msg, TimeStamp, (float) Data.Roll, (float) Data.Pitch, (float) Data.Yaw, (float) Speed.Roll, (float) Speed.Pitch, (float) Speed.Yaw); len = mavlink_msg_to_send_buffer(buf, &msg); bytes_sent = sendto(Mavlink->sock, buf, len, 0, (struct sockaddr *)&Mavlink->gcAddr, sizeof(struct sockaddr_in)); } printf("%s : Mavlink Status Arrêté\n", __FUNCTION__); pthread_exit(NULL); }
static int do_test (void) { pthread_mutexattr_t a; if (pthread_mutexattr_init (&a) != 0) { puts ("mutexattr_init failed"); return 1; } if (pthread_mutexattr_setrobust (&a, PTHREAD_MUTEX_ROBUST) != 0) { puts ("mutexattr_setrobust failed"); return 1; } #ifdef ENABLE_PI if (pthread_mutexattr_setprotocol (&a, PTHREAD_PRIO_INHERIT) != 0) { puts ("pthread_mutexattr_setprotocol failed"); return 1; } #endif int e; e = pthread_mutex_init (&m, &a); if (e != 0) { #ifdef ENABLE_PI if (e == ENOTSUP) { puts ("PI robust mutexes not supported"); return 0; } #endif puts ("mutex_init failed"); return 1; } if (pthread_mutexattr_destroy (&a) != 0) { puts ("mutexattr_destroy failed"); return 1; } if (pthread_barrier_init (&b, NULL, 2) != 0) { puts ("barrier_init failed"); return 1; } #define N 5 pthread_t th[N]; for (long int n = 0; n < N; ++n) { if (pthread_create (&th[n], NULL, tf, (void *) n) != 0) { printf ("pthread_create loop %ld failed\n", n + 1); return 1; } e = pthread_barrier_wait (&b); if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD) { printf ("parent: barrier_wait failed in round %ld\n", n + 1); return 1; } } if (pthread_mutex_lock (&m) != 0) { puts ("parent: mutex_lock failed"); return 1; } if (pthread_mutex_unlock (&m) != 0) { puts ("parent: mutex_unlock failed"); return 1; } if (pthread_cond_broadcast (&c) != 0) { puts ("cond_broadcast failed"); return 1; } for (int n = 0; n < N; ++n) { void *res; if (pthread_join (th[n], &res) != 0) { printf ("join round %d failed\n", n + 1); return 1; } if (res != PTHREAD_CANCELED) { printf ("thread %d not canceled\n", n + 1); return 1; } } e = pthread_mutex_lock (&m); if (e == 0) { puts ("parent: 2nd mutex_lock succeeded"); return 1; } if (e != EOWNERDEAD) { puts ("parent: mutex_lock did not return EOWNERDEAD"); return 1; } if (pthread_mutex_unlock (&m) != 0) { puts ("parent: 2nd mutex_unlock failed"); return 1; } if (pthread_mutex_destroy (&m) != 0) { puts ("mutex_destroy failed"); return 1; } return 0; }
/* A worker thread receives a number and a 4-letter name via targ */ void * tmain(void * targ) { /* Local variables are not shared with other threads */ int no, i; char name[5]; pthread_t tid; int isBooked[t];//Tells how many times train i has been booked by this thread. memset(isBooked, 0, sizeof(isBooked)); int trainsBooked[t];//Tells which all trains have been booked by this thread int numTrainsBooked = 0;//Count of the number of trains booked by this thread /* Retrieve my number and name from the parameter passed */ no = ((tinfo *)targ) -> tno; strcpy(name,((tinfo *)targ) -> tname); /* Retrieve my thread id */ tid = pthread_self(); while (1) { /* Check for termination condition */ pthread_mutex_lock(&donemutex); /* if the master thread is done */ if(mdone) { pthread_mutex_unlock(&donemutex); pthread_barrier_wait(&barrier); pthread_exit(NULL); } /* The master thread is still sleeping, so I continue to work */ pthread_mutex_unlock(&donemutex); //Check if number of active queries is less than MAX pthread_mutex_lock(&querymutex); if(numActiveQueries == MAX) { printf("\nThread %d : Blocked since active queries = MAX\n", no); pthread_cond_wait(&querycond, &querymutex); } numActiveQueries++; pthread_mutex_unlock(&querymutex); int a123; //Start query int queryType = 1 + rand()%3; if(queryType == INQUIRE) { inquiry(no); } else if(queryType == BOOK) { booking(no, isBooked, trainsBooked, &numTrainsBooked); } else { cancellation(no, isBooked, trainsBooked, &numTrainsBooked); } pthread_mutex_lock(&querymutex); numActiveQueries--; if(numActiveQueries == (MAX-1))//wake up a waiting query pthread_cond_signal(&querycond); pthread_mutex_unlock(&querymutex); sleep(SLEEPTIME); } }
static void *start_lock(void *arg) { pthread_mutex_lock(arg); pthread_barrier_wait(&barrier2); return 0; }
int uv_barrier_wait(uv_barrier_t* barrier) { int r = pthread_barrier_wait(barrier); if (r && r != PTHREAD_BARRIER_SERIAL_THREAD) abort(); return r == PTHREAD_BARRIER_SERIAL_THREAD; }
/* Do the forward Fast Fourier Transform either on two input images (the padded image and kernel) or on one image (the multiplication of the FFT of the two). In the second case, it is assumed that we are looking at the complex conjugate of the array so in practice this will be a backward transform. */ void twodimensionfft(struct convolveparams *p, struct fftonthreadparams *fp, int forward1backwardn1) { int err; pthread_t t; /* All thread ids saved in this, not used. */ pthread_attr_t attr; pthread_barrier_t b; size_t i, nb, *indexs, thrdcols; size_t nt=p->cp.numthreads, multiple=0; /* First we are going to get the 1D fourier transform on the rows of both images. */ if(forward1backwardn1==1) multiple=2; else if(forward1backwardn1==-1) multiple=1; else error(EXIT_FAILURE, 0, "%s: a bug! The value of the variable " "`forward1backwardn1' is %d not 1 or 2. Please contact us at %s " "so we can find the cause of the problem and fix it", __func__, forward1backwardn1, PACKAGE_BUGREPORT); /* ==================== */ /* 1D FFT on each row. */ /* ==================== */ gal_threads_dist_in_threads(multiple*p->ps0, nt, &indexs, &thrdcols); if(nt==1) { fp[0].stride=1; fp[0].indexs=&indexs[0]; fp[0].forward1backwardn1=forward1backwardn1; onedimensionfft(&fp[0]); } else { /* Initialize the attributes. Note that this running thread (that spinns off the nt threads) is also a thread, so the number the barrier should be one more than the number of threads spinned off. */ if( multiple*p->ps0 < nt ) nb=multiple*p->ps0+1; else nb=nt+1; gal_threads_attr_barrier_init(&attr, &b, nb); /* Spin off the threads: */ for(i=0;i<nt;++i) if(indexs[i*thrdcols]!=GAL_BLANK_SIZE_T) { fp[i].id=i; fp[i].b=&b; fp[i].stride=1; /* On each row, stride=1 */ fp[i].indexs=&indexs[i*thrdcols]; fp[i].forward1backwardn1=forward1backwardn1; err=pthread_create(&t, &attr, onedimensionfft, &fp[i]); if(err) error(EXIT_FAILURE, 0, "%s: can't create thread %zu for rows", __func__, i); } /* Wait for all threads to finish and free the spaces. */ pthread_barrier_wait(&b); pthread_attr_destroy(&attr); pthread_barrier_destroy(&b); } free(indexs); /* ====================== */ /* 1D FFT on each column. */ /* ====================== */ /* No comments, exact duplicate, except the p->ps1s! */ gal_threads_dist_in_threads(multiple*p->ps1, nt, &indexs, &thrdcols); if(nt==1) { fp[0].stride=p->ps1; fp[0].indexs=indexs; fp[0].forward1backwardn1=forward1backwardn1; onedimensionfft(&fp[0]); } else { if( multiple*p->ps1 < nt ) nb=multiple*p->ps1+1; else nb=nt+1; gal_threads_attr_barrier_init(&attr, &b, nb); for(i=0;i<nt;++i) if(indexs[i*thrdcols]!=GAL_BLANK_SIZE_T) { fp[i].b=&b; fp[i].stride=p->ps1; /* On each column, stride is p->ps1 */ fp[i].indexs=&indexs[i*thrdcols]; fp[i].forward1backwardn1=forward1backwardn1; err=pthread_create(&t, &attr, onedimensionfft, &fp[i]); if(err) error(EXIT_FAILURE, 0, "%s: can't create thread %zu for columns", __func__, i); } pthread_barrier_wait(&b); pthread_attr_destroy(&attr); pthread_barrier_destroy(&b); } free(indexs); }
static int do_one_test (void) { in_sh_body = 0; cleanups = 0; if (pipe (fd) != 0 || pipe (fd + 2) != 0) { puts ("pipe failed"); return 1; } pthread_t th; if (pthread_create (&th, NULL, tf, NULL) != 0) { puts ("create failed"); return 1; } int r = pthread_barrier_wait (&b); if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD) { puts ("parent thread: barrier_wait failed"); return 1; } sleep (1); r = pthread_kill (th, SIGHUP); if (r) { errno = r; printf ("pthread_kill failed %m\n"); return 1; } while (in_sh_body == 0) sleep (1); if (pthread_cancel (th) != 0) { puts ("cancel failed"); return 1; } /* This will cause the read in the child to return. */ close (fd[0]); close (fd[1]); close (fd[2]); close (fd[3]); void *ret; if (pthread_join (th, &ret) != 0) { puts ("join failed"); return 1; } if (ret != PTHREAD_CANCELED) { puts ("result is wrong"); return 1; } if (cleanups != 0x1234L) { printf ("called cleanups %lx\n", cleanups); return 1; } return 0; }
static void * tf (void *arg) { pthread_t th = (pthread_t) arg; int r = pthread_barrier_wait (&b); if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD) { puts ("parent thread: barrier_wait failed"); exit (1); } sleep (1); r = pthread_kill (th, SIGHUP); if (r) { errno = r; printf ("pthread_kill failed %m\n"); exit (1); } while (in_sh_body == 0) sleep (1); if (pthread_cancel (th) != 0) { puts ("cancel failed"); exit (1); } /* This will cause the read in the initial thread to return. */ close (fd[0]); close (fd[1]); close (fd[2]); close (fd[3]); void *ret; if (pthread_join (th, &ret) != 0) { puts ("join failed"); exit (1); } if (ret != PTHREAD_CANCELED) { puts ("result is wrong"); exit (1); } if (cleanups != 0x1234L) { printf ("called cleanups %lx\n", cleanups); exit (1); } if (pthread_barrier_destroy (&b)) { puts ("barrier destroy failed"); exit (1); } exit (0); }
hid_device * HID_API_EXPORT hid_open_path(const char *path) { int i; hid_device *dev = NULL; CFIndex num_devices; dev = new_hid_device(); /* Set up the HID Manager if it hasn't been done */ if (hid_init() < 0) return NULL; /* give the IOHIDManager a chance to update itself */ process_pending_events(); CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr); num_devices = CFSetGetCount(device_set); IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef)); CFSetGetValues(device_set, (const void **) device_array); for (i = 0; i < num_devices; i++) { char cbuf[BUF_LEN]; size_t len; IOHIDDeviceRef os_dev = device_array[i]; len = make_path(os_dev, cbuf, sizeof(cbuf)); if (!strcmp(cbuf, path)) { /* Matched Paths. Open this Device. */ IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeSeizeDevice); if (ret == kIOReturnSuccess) { char str[32]; free(device_array); CFRetain(os_dev); CFRelease(device_set); dev->device_handle = os_dev; /* Create the buffers for receiving data */ dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev); dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t)); /* Create the Run Loop Mode for this device. printing the reference seems to work. */ sprintf(str, "HIDAPI_%p", os_dev); dev->run_loop_mode = CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII); /* Attach the device to a Run Loop */ IOHIDDeviceRegisterInputReportCallback( os_dev, dev->input_report_buf, dev->max_input_report_len, &hid_report_callback, dev); IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev); /* Start the read thread */ pthread_create(&dev->thread, NULL, read_thread, dev); /* Wait here for the read thread to be initialized. */ pthread_barrier_wait(&dev->barrier); return dev; } else { goto return_error; } } } return_error: free(device_array); CFRelease(device_set); free_hid_device(dev); return NULL; }
static void *read_thread(void *param) { hid_device *dev = param; SInt32 code; /* Move the device's run loop to this thread. */ IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode); /* Create the RunLoopSource which is used to signal the event loop to stop when hid_close() is called. */ CFRunLoopSourceContext ctx; memset(&ctx, 0, sizeof(ctx)); ctx.version = 0; ctx.info = dev; ctx.perform = &perform_signal_callback; dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx); CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode); /* Store off the Run Loop so it can be stopped from hid_close() and on device disconnection. */ dev->run_loop = CFRunLoopGetCurrent(); /* Notify the main thread that the read thread is up and running. */ pthread_barrier_wait(&dev->barrier); /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input reports into the hid_report_callback(). */ while (!dev->shutdown_thread && !dev->disconnected) { code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE); /* Return if the device has been disconnected */ if (code == kCFRunLoopRunFinished) { dev->disconnected = 1; break; } /* Break if The Run Loop returns Finished or Stopped. */ if (code != kCFRunLoopRunTimedOut && code != kCFRunLoopRunHandledSource) { /* There was some kind of error. Setting shutdown seems to make sense, but there may be something else more appropriate */ dev->shutdown_thread = 1; break; } } /* Now that the read thread is stopping, Wake any threads which are waiting on data (in hid_read_timeout()). Do this under a mutex to make sure that a thread which is about to go to sleep waiting on the condition acutally will go to sleep before the condition is signaled. */ pthread_mutex_lock(&dev->mutex); pthread_cond_broadcast(&dev->condition); pthread_mutex_unlock(&dev->mutex); /* Wait here until hid_close() is called and makes it past the call to CFRunLoopWakeUp(). This thread still needs to be valid when that function is called on the other thread. */ pthread_barrier_wait(&dev->shutdown_barrier); return NULL; }
void *find_lowest(void *arguments) { t_data *args = arguments; //shove the data into a structure int thread_id = args->thread_id; int num_threads = args->num_threads; int size = args->size; pos *working_list = args->working_list; pos *min_cells = args->min_cells; int *matrix = args->matrix; int *mask = args->mask; int nfill = args->nfill; /*Select a minumum and fill a cell until *the desired amount of cells are filled */ while(filled < nfill) { /* Determines the local minimum of each thread. * Updates the smallest value found each time. */ //min for individual position pos local_min; local_min.x = -1; local_min.y = -1; local_min.value = INT_MAX; pos surround[4]; /* 0 is top * 1 is right * 2 is bottom * 3 is left */ int i; for(i = 0; i < 4; i++) { surround[i].value = INT_MAX; surround[i].x = -1; surround[i].y = -1; } //should only execute if thread_id is larger than filled //this loop exits after the working_list has been exausted for(i = thread_id; i < filled; i = i + num_threads) { //find position represented by working_list[i] x and y int position = size * working_list[i].y + working_list[i].x; //printf("%d\n", position); //find the top position if(position - size >= 0) { surround[0].value = matrix[position - size]; surround[0].x = working_list[i].x; surround[0].y = working_list[i].y - 1; } //find the right position if(working_list[i].x + 1 < size) { surround[1].value = matrix[position + 1]; surround[1].x = working_list[i].x + 1; surround[1].y = working_list[i].y; } //find bottom position if(position + size < size * size) { surround[2].value = matrix[position + size]; surround[2].x = working_list[i].x; surround[2].y = working_list[i].y + 1; } //find left position if(working_list[i].x - 1 >= 0) { surround[3].value = matrix[position - 1]; surround[3].x = working_list[i].x - 1; surround[3].y = working_list[i].y; } //find the minimum among the surrounding positions int j; for(j = 0; j < 4; j++) { //set min to the new position if(surround[j].value != -1 && surround[j].value < local_min.value) { local_min.value = surround[j].value; local_min.x = surround[j].x; local_min.y = surround[j].y; } } //determine if the local min is smaller than the minimum found so far if(local_min.value < min_cells[thread_id].value) { min_cells[thread_id] = local_min; } local_min.value = INT_MAX; local_min.x = -1; local_min.y = -1; } //BARRIER: Wait for all other threads to find their minimum cell pthread_barrier_wait(&barrier); //Thread 0 manages the matrix, mask, working list, and filled cell count if(thread_id == 0) { pos global_min; global_min.value = INT_MAX; global_min.x = -1; global_min.y = -1; //determine minimum cell int k; for(k = 0; k < num_threads; k++) { if(min_cells[k].value < global_min.value) //set new min { global_min = min_cells[k]; } } //determine linear position of cell int position = size * global_min.y + global_min.x; //fill the cell in the mask mask[position] = 1; //set the value in the matrix to "used" matrix[position] = -1; //add latest cell to the working list working_list[filled] = global_min; //count one more cell filled filled++; int m; for(m = 0; m < num_threads; m++) { min_cells[m].value = INT_MAX; min_cells[m].x = -1; min_cells[m].y = -1; } } //BARRIER: All other threads wait for Thread 0 to finish working pthread_barrier_wait(&barrier); } }
static void check_threads (pthread_barrier_t *barrier) { pthread_barrier_wait (barrier); }
void* sender(void* id) { sleep(1); pthread_barrier_wait(&bar); pthread_kill(*((pthread_t*)id), SIGALRM); return NULL; }
static int do_test (void) { if (pthread_barrier_init (&b, NULL, N + 1) != 0) { puts ("barrier_init failed"); return 1; } pthread_mutex_lock (&mut); int i, j, err; pthread_t th[N]; for (i = 0; i < N; ++i) if ((err = pthread_create (&th[i], NULL, tf, NULL)) != 0) { printf ("cannot create thread %d: %s\n", i, strerror (err)); return 1; } for (i = 0; i < ROUNDS; ++i) { pthread_cond_wait (&cond2, &mut); if (i & 1) pthread_mutex_unlock (&mut); if (i & 2) pthread_cond_broadcast (&cond); else if (i & 4) for (j = 0; j < N; ++j) pthread_cond_signal (&cond); else { for (j = 0; j < (i / 8) % N; ++j) pthread_cond_signal (&cond); pthread_cond_broadcast (&cond); } if ((i & 1) == 0) pthread_mutex_unlock (&mut); err = pthread_cond_destroy (&cond); if (err) { printf ("pthread_cond_destroy failed: %s\n", strerror (err)); return 1; } /* Now clobber the cond variable which has been successfully destroyed above. */ memset (&cond, (char) i, sizeof (cond)); err = pthread_barrier_wait (&b); if (err != 0 && err != PTHREAD_BARRIER_SERIAL_THREAD) { puts ("parent: barrier_wait failed"); return 1; } pthread_mutex_lock (&mut); err = pthread_barrier_wait (&b); if (err != 0 && err != PTHREAD_BARRIER_SERIAL_THREAD) { puts ("parent: barrier_wait failed"); return 1; } count = 0; err = pthread_cond_init (&cond, NULL); if (err) { printf ("pthread_cond_init failed: %s\n", strerror (err)); return 1; } } for (i = 0; i < N; ++i) if ((err = pthread_join (th[i], NULL)) != 0) { printf ("failed to join thread %d: %s\n", i, strerror (err)); return 1; } puts ("done"); return 0; }
void * masterThread (void * arg) { int dither = (int)(size_t)arg; timeout = (int)(size_t)arg; pthread_barrier_wait(&startBarrier); do { int sleepTime; assert(pthread_mutex_lock(&control.mx) == 0); control.value = timeout; assert(pthread_mutex_unlock(&control.mx) == 0); /* * We are attempting to send the signal close to when the slave * is due to timeout. We feel around by adding some [non-random] dither. * * dither is in the range 2*timeout peak-to-peak * sleep time is the average of timeout plus dither. * e.g. * if timeout = 10 then dither = 20 and * sleep millisecs is: 5 <= ms <= 15 * * The bias value attempts to apply some negative feedback to keep * the ratio of timeouts to signals taken close to 1:1. * bias changes more slowly than dither so as to average more. * * Finally, if abs(bias) exceeds timeout then timeout is incremented. */ if (signalsSent % timeout == 0) { if (timeoutCount > signalsTakenCount) { bias++; } else if (timeoutCount < signalsTakenCount) { bias--; } if (bias < -timeout || bias > timeout) { timeout++; } } dither = (dither + 1 ) % (timeout * 2); sleepTime = (timeout - bias + dither) / 2; Sleep(sleepTime); assert(pthread_cond_signal(&control.cv) == 0); signalsSent++; pthread_barrier_wait(&holdBarrier); pthread_barrier_wait(&readyBarrier); } while (!allExit); return NULL; }
void *compute(void *s){ int pnum = *((int *) s); double *resultArray = (double *) malloc(numberofRows * sizeof(double)); double *normalValue = (double *) malloc(2 * sizeof(double)); int c, i; // int a = 0; struct row *pData; double partitionSum = 0; normalValue[1] = 0; pData = &partitionedMatrixData[pnum]; // totalSumAtEachPartition[pnum] = 0; do { //pData = &partitionedMatrixData[pnum]; partitionSum = 0; for (c=0; c < pData->rcount; c++) { double rowSum = 0; //Loop through each column for (i=0; i < pData->rowary[c].vcount; i++) { //printf("pData->rowary[c].col[i]: %li\n", pData->rowary[c].col[i] + (pData->rowary[c].col[i]*255)); // rowSum = rowSum + (pData->rowary[c].values[i] * multiplyArray[pData->rowary[c].col[i] + (pData->rowary[c].col[i]*50)]); rowSum = rowSum + (pData->rowary[c].values[i] * multiplyArray[pData->rowary[c].col[i]]); } resultArray[pData->rowary[c].rowId] = rowSum; partitionSum = partitionSum + pow(rowSum, 2); } // totalSumAtEachPartition[pnum] = partitionSum; pthread_mutex_lock(&sumLock); totalSum = totalSum + partitionSum; pthread_mutex_unlock(&sumLock); pthread_barrier_wait(&barr); if (pnum == 0){ // double totalSum2 = 0; // for (i=0; i<max_threads; i++) { //Alternative is to have a global sum and use locks. // totalSum2 = totalSum2 + totalSumAtEachPartition[i]; // totalSumAtEachPartition[i] = 0; // } // norm = sqrt(totalSum2); norm = sqrt(totalSum); totalSum = 0; } // a++; normalValue[0] = normalValue[1]; pthread_barrier_wait(&barr); normalValue[1] = norm; for (c=0; c<pData->rcount; c++) { multiplyArray[pData->rowary[c].rowId] = resultArray[pData->rowary[c].rowId]; resultArray[pData->rowary[c].rowId] = 0; } pthread_barrier_wait(&barr); } while(normalValue[0] == 0 || ((normalValue[0] - normalValue[1]) > 10E-7) || ((normalValue[1] - normalValue[0]) > 10E-7)); free(s); free(normalValue); free(resultArray); pthread_exit(0); }
static int do_test (void) { char tmp[] = "/tmp/tst-signal1-XXXXXX"; int fd = mkstemp (tmp); if (fd == -1) { puts ("mkstemp failed"); exit (1); } unlink (tmp); int i; for (i = 0; i < 20; ++i) write (fd, "foobar xyzzy", 12); b = mmap (NULL, sizeof (pthread_barrier_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (b == MAP_FAILED) { puts ("mmap failed"); exit (1); } pthread_barrierattr_t ba; if (pthread_barrierattr_init (&ba) != 0) { puts ("barrierattr_init failed"); exit (1); } if (pthread_barrierattr_setpshared (&ba, PTHREAD_PROCESS_SHARED) != 0) { puts ("barrierattr_setpshared failed"); exit (1); } if (pthread_barrier_init (b, &ba, 2) != 0) { puts ("barrier_init failed"); exit (1); } if (pthread_barrierattr_destroy (&ba) != 0) { puts ("barrierattr_destroy failed"); exit (1); } pid_t pid = fork (); if (pid == -1) { puts ("fork failed"); exit (1); } if (pid == 0) receiver (); pthread_barrier_wait (b); /* Wait a bit more. */ struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 }; nanosleep (&ts, NULL); /* Send the signal. */ puts ("sending the signal now"); kill (pid, SIGINT); /* Wait for the process to terminate. */ int status; if (TEMP_FAILURE_RETRY (waitpid (pid, &status, 0)) != pid) { puts ("wrong child reported terminated"); exit (1); } if (!WIFSIGNALED (status)) { puts ("child wasn't signalled"); exit (1); } if (WTERMSIG (status) != SIGINT) { puts ("child not terminated with SIGINT"); exit (1); } return 0; }
static unsigned long long int tsdiff (const struct timespec *before, const struct timespec *after) { struct timespec diff = { .tv_sec = after->tv_sec - before->tv_sec, .tv_nsec = after->tv_nsec - before->tv_nsec }; while (diff.tv_nsec < 0) { --diff.tv_sec; diff.tv_nsec += 1000000000; } return diff.tv_sec * 1000000000ULL + diff.tv_nsec; } static unsigned long long int test_nanosleep (clockid_t clock, const char *which, const struct timespec *before, int *bad) { const struct timespec sleeptime = { .tv_nsec = 100000000 }; int e = clock_nanosleep (clock, 0, &sleeptime, NULL); if (e == EINVAL || e == ENOTSUP || e == ENOSYS) { printf ("clock_nanosleep not supported for %s CPU clock: %s\n", which, strerror (e)); return 0; } if (e != 0) { printf ("clock_nanosleep on %s CPU clock: %s\n", which, strerror (e)); *bad = 1; return 0; } struct timespec after; if (clock_gettime (clock, &after) < 0) { printf ("clock_gettime on %s CPU clock %lx => %s\n", which, (unsigned long int) clock, strerror (errno)); *bad = 1; return 0; } unsigned long long int diff = tsdiff (before, &after); if (diff < sleeptime.tv_nsec || diff > sleeptime.tv_nsec * 2) { printf ("clock_nanosleep on %s slept %llu (outside reasonable range)\n", which, diff); *bad = 1; return diff; } struct timespec sleeptimeabs = sleeptime; sleeptimeabs.tv_sec += after.tv_sec; sleeptimeabs.tv_nsec += after.tv_nsec; while (sleeptimeabs.tv_nsec >= 1000000000) { ++sleeptimeabs.tv_sec; sleeptimeabs.tv_nsec -= 1000000000; } e = clock_nanosleep (clock, TIMER_ABSTIME, &sleeptimeabs, NULL); if (e != 0) { printf ("absolute clock_nanosleep on %s CPU clock: %s\n", which, strerror (e)); *bad = 1; return diff; } struct timespec afterabs; if (clock_gettime (clock, &afterabs) < 0) { printf ("clock_gettime on %s CPU clock %lx => %s\n", which, (unsigned long int) clock, strerror (errno)); *bad = 1; return diff; } unsigned long long int sleepdiff = tsdiff (&sleeptimeabs, &afterabs); if (sleepdiff > sleeptime.tv_nsec) { printf ("\ absolute clock_nanosleep on %s %llu past target (outside reasonable range)\n", which, sleepdiff); *bad = 1; } unsigned long long int diffabs = tsdiff (&after, &afterabs); if (diffabs < sleeptime.tv_nsec || diffabs > sleeptime.tv_nsec * 2) { printf ("\ absolute clock_nanosleep on %s slept %llu (outside reasonable range)\n", which, diffabs); *bad = 1; } return diff + diffabs; } static int do_test (void) { int result = 0; clockid_t process_clock, th_clock, my_thread_clock; int e; pthread_t th; e = clock_getcpuclockid (0, &process_clock); if (e != 0) { printf ("clock_getcpuclockid on self => %s\n", strerror (e)); return 1; } e = pthread_getcpuclockid (pthread_self (), &my_thread_clock); if (e != 0) { printf ("pthread_getcpuclockid on self => %s\n", strerror (e)); return 1; } /* This is a kludge. This test fails if the semantics of thread and process clocks are wrong. The old code using hp-timing without kernel support has bogus semantics if there are context switches. We don't fail to report failure when the proper functionality is not available in the kernel. It so happens that Linux kernels without correct CPU clock support also lack CPU timer support, so we use use that to guess that we are using the bogus code and not test it. */ timer_t t; if (timer_create (my_thread_clock, NULL, &t) != 0) { printf ("timer_create: %m\n"); puts ("No support for CPU clocks with good semantics, skipping test"); return 0; } timer_delete (t); pthread_barrier_init (&barrier, NULL, 2); e = pthread_create (&th, NULL, chew_cpu, NULL); if (e != 0) { printf ("pthread_create: %s\n", strerror (e)); return 1; } e = pthread_getcpuclockid (th, &th_clock); if (e == ENOENT || e == ENOSYS || e == ENOTSUP) { puts ("pthread_getcpuclockid does not support other threads"); return 1; } pthread_barrier_wait (&barrier); struct timespec res; if (clock_getres (th_clock, &res) < 0) { printf ("clock_getres on live thread clock %lx => %s\n", (unsigned long int) th_clock, strerror (errno)); result = 1; return 1; } printf ("live thread clock %lx resolution %lu.%.9lu\n", (unsigned long int) th_clock, res.tv_sec, res.tv_nsec); struct timespec process_before, process_after; if (clock_gettime (process_clock, &process_before) < 0) { printf ("clock_gettime on process clock %lx => %s\n", (unsigned long int) process_clock, strerror (errno)); return 1; } struct timespec before, after; if (clock_gettime (th_clock, &before) < 0) { printf ("clock_gettime on live thread clock %lx => %s\n", (unsigned long int) th_clock, strerror (errno)); return 1; } printf ("live thread before sleep => %lu.%.9lu\n", before.tv_sec, before.tv_nsec); struct timespec me_before, me_after; if (clock_gettime (my_thread_clock, &me_before) < 0) { printf ("clock_gettime on self thread clock %lx => %s\n", (unsigned long int) my_thread_clock, strerror (errno)); return 1; } printf ("self thread before sleep => %lu.%.9lu\n", me_before.tv_sec, me_before.tv_nsec); struct timespec sleeptime = { .tv_nsec = 500000000 }; if (nanosleep (&sleeptime, NULL) != 0) { perror ("nanosleep"); return 1; } if (clock_gettime (th_clock, &after) < 0) { printf ("clock_gettime on live thread clock %lx => %s\n", (unsigned long int) th_clock, strerror (errno)); return 1; } printf ("live thread after sleep => %lu.%.9lu\n", after.tv_sec, after.tv_nsec); if (clock_gettime (process_clock, &process_after) < 0) { printf ("clock_gettime on process clock %lx => %s\n", (unsigned long int) process_clock, strerror (errno)); return 1; } if (clock_gettime (my_thread_clock, &me_after) < 0) { printf ("clock_gettime on self thread clock %lx => %s\n", (unsigned long int) my_thread_clock, strerror (errno)); return 1; } printf ("self thread after sleep => %lu.%.9lu\n", me_after.tv_sec, me_after.tv_nsec); unsigned long long int th_diff = tsdiff (&before, &after); unsigned long long int pdiff = tsdiff (&process_before, &process_after); unsigned long long int my_diff = tsdiff (&me_before, &me_after); if (th_diff < 100000000 || th_diff > 600000000) { printf ("live thread before - after %llu outside reasonable range\n", th_diff); result = 1; } if (my_diff > 100000000) { printf ("self thread before - after %llu outside reasonable range\n", my_diff); result = 1; } if (pdiff < th_diff) { printf ("process before - after %llu outside reasonable range (%llu)\n", pdiff, th_diff); result = 1; } process_after.tv_nsec += test_nanosleep (th_clock, "live thread", &after, &result); process_after.tv_nsec += test_nanosleep (process_clock, "process", &process_after, &result); test_nanosleep (CLOCK_PROCESS_CPUTIME_ID, "PROCESS_CPUTIME_ID", &process_after, &result); pthread_cancel (th); e = clock_nanosleep (CLOCK_THREAD_CPUTIME_ID, 0, &sleeptime, NULL); if (e != EINVAL) { printf ("clock_nanosleep CLOCK_THREAD_CPUTIME_ID: %s\n", strerror (e)); result = 1; } return result; }
//################################################################################################## static void *magma_sapplyQ_m_parallel_section(void *arg) { magma_int_t my_core_id = ((magma_sapplyQ_m_id_data*)arg) -> id; magma_sapplyQ_m_data* data = ((magma_sapplyQ_m_id_data*)arg) -> data; magma_int_t nrgpu = data -> nrgpu; magma_int_t allcores_num = data -> threads_num; magma_int_t n = data -> n; magma_int_t ne = data -> ne; magma_int_t n_gpu = data -> n_gpu; magma_int_t nb = data -> nb; magma_int_t Vblksiz = data -> Vblksiz; float *E = data -> E; magma_int_t lde = data -> lde; float *V = data -> V; magma_int_t ldv = data -> ldv; float *TAU = data -> TAU; float *T = data -> T; magma_int_t ldt = data -> ldt; pthread_barrier_t* barrier = &(data -> barrier); magma_int_t info; #ifdef ENABLE_TIMER real_Double_t timeQcpu=0.0, timeQgpu=0.0; #endif magma_int_t n_cpu = ne - n_gpu; // with MKL and when using omp_set_num_threads instead of mkl_set_num_threads // it need that all threads setting it to 1. magma_set_lapack_numthreads(1); #ifdef MAGMA_SETAFFINITY //#define PRINTAFFINITY #ifdef PRINTAFFINITY affinity_set print_set; print_set.print_affinity(my_core_id, "starting affinity"); #endif affinity_set original_set; affinity_set new_set(my_core_id); int check = 0; int check2 = 0; // bind threads check = original_set.get_affinity(); if (check == 0) { check2 = new_set.set_affinity(); if (check2 != 0) printf("Error in sched_setaffinity (single cpu)\n"); } else { printf("Error in sched_getaffinity\n"); } #ifdef PRINTAFFINITY print_set.print_affinity(my_core_id, "set affinity"); #endif #endif if (my_core_id == 0) { //============================================= // on GPU on thread 0: // - apply V2*Z(:,1:N_GPU) //============================================= #ifdef ENABLE_TIMER timeQgpu = magma_wtime(); #endif magma_sbulge_applyQ_v2_m(nrgpu, MagmaLeft, n_gpu, n, nb, Vblksiz, E, lde, V, ldv, T, ldt, &info); magma_device_sync(); #ifdef ENABLE_TIMER timeQgpu = magma_wtime()-timeQgpu; printf(" Finish Q2_GPU GGG timing= %f\n", timeQgpu); #endif } else { //============================================= // on CPU on threads 1:allcores_num-1: // - apply V2*Z(:,N_GPU+1:NE) //============================================= #ifdef ENABLE_TIMER if (my_core_id == 1) timeQcpu = magma_wtime(); #endif magma_int_t n_loc = magma_ceildiv(n_cpu, allcores_num-1); float* E_loc = E + (n_gpu+ n_loc * (my_core_id-1))*lde; n_loc = min(n_loc,n_cpu - n_loc * (my_core_id-1)); magma_stile_bulge_applyQ(my_core_id, MagmaLeft, n_loc, n, nb, Vblksiz, E_loc, lde, V, ldv, TAU, T, ldt); pthread_barrier_wait(barrier); #ifdef ENABLE_TIMER if (my_core_id == 1) { timeQcpu = magma_wtime()-timeQcpu; printf(" Finish Q2_CPU CCC timing= %f\n", timeQcpu); } #endif } // END if my_core_id #ifdef MAGMA_SETAFFINITY // unbind threads if (check == 0) { check2 = original_set.set_affinity(); if (check2 != 0) printf("Error in sched_setaffinity (restore cpu list)\n"); } #ifdef PRINTAFFINITY print_set.print_affinity(my_core_id, "restored_affinity"); #endif #endif return 0; }
/* 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; }
void *work(void *thread_arg) { int num_access = 0; thread_params *thread_param = (thread_params*)thread_arg; int tid = thread_param->thread_id; //double service_time = 0.001; // 1e-3 long cycles_in_service = CPU_FREQ/1000; int cycles_in_wait = cycles_in_service/2; //int initial_loop_flag = 1; timestamp tss[MAX_N_ACCESS]; //timsstampes int count = 0; set_affinity(threads[tid], &cpuset[tid]); uint64_t start_time = read_tsc_fenced(); long experiment_time = EXPERIMENT_TIME_IN_SEC*CPU_FREQ; uint64_t start = read_tsc_fenced(); while(!start_work_flag) ; while(read_tsc_fenced() - start_time < experiment_time) { start = read_tsc_fenced(); while(read_tsc_fenced() - start < cycles_in_wait) ; uint64_t getlock_time = read_tsc_fenced(); dprintf("Thread %d trying to get the lock at %lu \n",tid,getlock_time); pthread_spin_lock(thread_param->spinlock_ptr); /************The critical section***************/ uint64_t get_in_cs_time = read_tsc_fenced(); dprintf("Thread %d got the lock at %lu \n",tid, get_in_cs_time); //get_lock_time[access_count] = get_in_cs_time; tss[count++].ts = get_in_cs_time; num_access++; while(read_tsc_fenced() - get_in_cs_time < cycles_in_wait) { } tss[count++].ts = read_tsc_fenced(); pthread_spin_unlock(thread_param->spinlock_ptr); /************End the critical section***************/ uint64_t end_cs_time = read_tsc_fenced(); dprintf("Thread %d released the lock at %lu \n",tid, tss[count - 1]); time_in_cs[tid] += (end_cs_time - getlock_time)/(double)CPU_FREQ; } // make sure all threads have finished before fiddling with the spinlock again pthread_barrier_wait (&fin_barrier); num_access_each_thread[tid] = num_access; //when the experiment is done, write to the global timestamp array pthread_spin_lock(thread_param->spinlock_ptr); for(int i = 0; i < count; i++) { g_tss[access_count].ts = tss[i].ts; g_tss[access_count].id = tid; access_count++ ; } pthread_spin_unlock(thread_param->spinlock_ptr); }
/* The processing loop. Kinda superstep style, everyone copies, everyone averages and then everyone checks if they're done. Will quit when every thread says it has finished. */ void* threadLoop( void* inData) { LoopData* theData = (LoopData*) inData; int i, diff = 0; // Little bit of indirection to make access easier/simpler float** currArray = theData->inArray; float** nextArray = theData->outArray; int arrayX = theData->arrayX; int arrayY = theData->arrayY; float precision = theData->precision; int* finishedThreads = theData->finishedThreads; for( i = 0; i < arrayX; i++) { memcpy(nextArray[i], theData->inArray[i], arrayY * sizeof(float)); } while( 1 ) { //copy the next array into the working copy. for( i = 1; i < arrayX - 1; i++) { memcpy(currArray[i], nextArray[i], arrayY * sizeof(float)); } //Wait until everyones done that if(theData->barrier != NULL) { pthread_barrier_wait(theData->barrier); } averageFour(currArray, nextArray, arrayX, arrayY); diff = checkDiff(currArray, nextArray, arrayX, arrayY, precision); if (diff != 0) { if(theData->finLock != NULL) { pthread_mutex_lock(theData->finLock); } (*finishedThreads)++; if(theData->finLock != NULL) { pthread_mutex_unlock(theData->finLock); } } // Wait for everyone again if(theData->barrier != NULL) { pthread_barrier_wait(theData->barrier); } // If everyone is done we can go if ((*finishedThreads) == theData->numThreads) { break; } else //otherwise we have to try again { (*finishedThreads) = 0; // Didn't lock as we're setting to a constant and the only other // modification of the variable is behind a barrier in the loop. } } return 0; }
static int do_test (void) { int status = 0; if (pthread_barrier_init (&b, NULL, 2) != 0) { puts ("barrier_init failed"); return 1; } pthread_t th; if (pthread_create (&th, NULL, tf, NULL) != 0) { puts ("1st create failed"); return 1; } int e = pthread_barrier_wait (&b); if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD) { puts ("1st barrier_wait failed"); return 1; } if (pthread_mutex_lock (&m) != 0) { puts ("1st mutex_lock failed"); return 1; } if (pthread_cond_signal (&c) != 0) { puts ("1st cond_signal failed"); return 1; } if (pthread_cancel (th) != 0) { puts ("cancel failed"); return 1; } if (pthread_mutex_unlock (&m) != 0) { puts ("1st mutex_unlock failed"); return 1; } void *res; if (pthread_join (th, &res) != 0) { puts ("1st join failed"); return 1; } if (res != PTHREAD_CANCELED) { puts ("first thread not canceled"); status = 1; } #ifndef OPAQUE_STRUCTS printf ("cond = { %d, %x, %lld, %lld, %lld, %p, %u, %u }\n", c.__data.__lock, c.__data.__futex, c.__data.__total_seq, c.__data.__wakeup_seq, c.__data.__woken_seq, c.__data.__mutex, c.__data.__nwaiters, c.__data.__broadcast_seq); #endif if (pthread_create (&th, NULL, tf, (void *) 1l) != 0) { puts ("2nd create failed"); return 1; } e = pthread_barrier_wait (&b); if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD) { puts ("2nd barrier_wait failed"); return 1; } if (pthread_mutex_lock (&m) != 0) { puts ("2nd mutex_lock failed"); return 1; } if (pthread_cond_signal (&c) != 0) { puts ("2nd cond_signal failed"); return 1; } if (pthread_mutex_unlock (&m) != 0) { puts ("2nd mutex_unlock failed"); return 1; } if (pthread_join (th, &res) != 0) { puts ("2nd join failed"); return 1; } if (res != NULL) { puts ("2nd thread canceled"); status = 1; } #ifndef OPAQUE_STRUCTS printf ("cond = { %d, %x, %lld, %lld, %lld, %p, %u, %u }\n", c.__data.__lock, c.__data.__futex, c.__data.__total_seq, c.__data.__wakeup_seq, c.__data.__woken_seq, c.__data.__mutex, c.__data.__nwaiters, c.__data.__broadcast_seq); #endif return status; }
static void *read_thread(void *param) { hid_device *dev = param; unsigned char *buf; const size_t length = dev->input_ep_max_packet_size; /* Set up the transfer object. */ buf = malloc(length); dev->transfer = libusb_alloc_transfer(0); libusb_fill_interrupt_transfer(dev->transfer, dev->device_handle, dev->input_endpoint, buf, length, read_callback, dev, 5000/*timeout*/); /* Make the first submission. Further submissions are made from inside read_callback() */ libusb_submit_transfer(dev->transfer); /* Notify the main thread that the read thread is up and running. */ pthread_barrier_wait(&dev->barrier); /* Handle all the events. */ while (!dev->shutdown_thread) { int res; res = libusb_handle_events(usb_context); if (res < 0) { /* There was an error. */ LOG("read_thread(): libusb reports error # %d\n", res); /* Break out of this loop only on fatal error.*/ if (res != LIBUSB_ERROR_BUSY && res != LIBUSB_ERROR_TIMEOUT && res != LIBUSB_ERROR_OVERFLOW && res != LIBUSB_ERROR_INTERRUPTED) { break; } } } /* Cancel any transfer that may be pending. This call will fail if no transfers are pending, but that's OK. */ libusb_cancel_transfer(dev->transfer); while (!dev->cancelled) libusb_handle_events_completed(usb_context, &dev->cancelled); /* Now that the read thread is stopping, Wake any threads which are waiting on data (in hid_read_timeout()). Do this under a mutex to make sure that a thread which is about to go to sleep waiting on the condition acutally will go to sleep before the condition is signaled. */ pthread_mutex_lock(&dev->mutex); pthread_cond_broadcast(&dev->condition); pthread_mutex_unlock(&dev->mutex); /* The dev->transfer->buffer and dev->transfer objects are cleaned up in hid_close(). They are not cleaned up here because this thread could end either due to a disconnect or due to a user call to hid_close(). In both cases the objects can be safely cleaned up after the call to pthread_join() (in hid_close()), but since hid_close() calls libusb_cancel_transfer(), on these objects, they can not be cleaned up here. */ return NULL; }
void * thread_barrier_wait(void * arg) { pthread_barrier_wait(&barrier); }
static void * func3(void *arg) { char *fn = "func3"; int i; int j; int sts; FILE *f; if ((f = fopen("/tmp/func3.out", "w")) == NULL) { perror("func3 fopen"); pthread_exit("botch"); } j = pmUseContext(ctx3); if ( j < 0) { fprintf(f, "Error: %s: pmUseContext(%d) -> %s\n", fn, ctx3, pmErrStr(j)); fclose(f); pthread_exit("botch"); } pthread_barrier_wait(&barrier); for (j = 0; j < 100; j++) { for (i = 0; i < NMETRIC; i += 2) { if (ctx3 != ctx2) { /* * limit sampledso.bin [2] in context 3 * - exclude instances below, leaving 7 instances 200, ... 800 */ int instlist[] = { 100, 900 }; if ((sts = pmAddProfile(desclist[2].indom, 0, NULL)) < 0) { fprintf(f, "Error: pmAddProfile(%s) -> %s\n", namelist[2], pmErrStr(sts)); fclose(f); pthread_exit("botch"); } if ((sts = pmDelProfile(desclist[2].indom, sizeof(instlist)/sizeof(instlist[0]), instlist)) < 0) { fprintf(f, "Error: pmDelProfile(%s) -> %s\n", namelist[2], pmErrStr(sts)); fclose(f); pthread_exit("botch"); } } else { pthread_mutex_lock(&mymutex); if ((sts = pmAddProfile(desclist[1].indom, 0, NULL)) < 0) { fprintf(f, "Error: pmAddProfile(%s) -> %s\n", namelist[1], pmErrStr(sts)); fclose(f); pthread_exit("botch"); } } foo(f, fn, i); if (ctx3 == ctx2) pthread_mutex_unlock(&mymutex); } for (i = 1; i < NMETRIC; i += 2) { /* inherit instance profile from loop above */ if (ctx3 == ctx2) { pthread_mutex_lock(&mymutex); if ((sts = pmAddProfile(desclist[1].indom, 0, NULL)) < 0) { fprintf(f, "Error: pmAddProfile(%s) -> %s\n", namelist[1], pmErrStr(sts)); fclose(f); pthread_exit("botch"); } } foo(f, fn, i); if (ctx3 == ctx2) pthread_mutex_unlock(&mymutex); } } fclose(f); pthread_exit(NULL); }
int main() { int cnt = 0; int rc; pthread_t child_thread; sig_rcvd = 0; barrier_waited = 0; printf("Initialize barrier with count = 2\n"); if(pthread_barrier_init(&barrier, NULL, 2) != 0) { printf("main: Error at pthread_barrier_init()\n"); return PTS_UNRESOLVED; } printf("main: create child thread\n"); thread_state = NOT_CREATED_THREAD; if(pthread_create(&child_thread, NULL, fn_chld, NULL) != 0) { printf("main: Error at pthread_create()\n"); return PTS_UNRESOLVED; } /* Expect the child to block*/ cnt = 0; do{ sleep(1); }while (thread_state !=EXITING_THREAD && cnt++ < 2); if(thread_state == EXITING_THREAD) { /* child thread did not block */ printf("Test FAILED: child thread did not block on " "pthread_barrier_wait()\n"); exit(PTS_FAIL); } else if(thread_state != ENTERED_THREAD) { printf("Unexpected thread state\n"); exit(PTS_UNRESOLVED); } printf("main: send SIGUSR1 to child thread\n"); if(pthread_kill(child_thread, SIGUSR1) != 0) { printf("main: Error at pthread_kill()\n"); exit(PTS_UNRESOLVED); } /* Wait for thread to receive the signal */ while(sig_rcvd != 1) { sleep(1); } printf("main: call barrier wait\n"); rc = pthread_barrier_wait(&barrier); if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) { printf("Test FAILED: main: pthread_barrier_wait() got unexpected " "return code : %d\n" , rc); exit(PTS_FAIL); } else if(rc == PTHREAD_BARRIER_SERIAL_THREAD) printf("main: got PTHREAD_BARRIER_SERIAL_THREAD\n"); barrier_waited = 1; /* We expected the child returned from barrier wait */ cnt = 0; do{ sleep(1); }while (thread_state != EXITING_THREAD && cnt++ < 3); if(thread_state == ENTERED_THREAD) { printf("Test FAILED: child thread still blocked on " "barrier wait\n"); return PTS_FAIL; } else if(thread_state != EXITING_THREAD) { printf("main: Unexpected thread state\n"); return PTS_UNRESOLVED; } if(pthread_join(child_thread, NULL) != 0) { printf("main: Error at pthread_join()\n"); exit(PTS_UNRESOLVED); } if(pthread_barrier_destroy(&barrier) != 0) { printf("Error at pthread_barrier_destroy()"); return PTS_UNRESOLVED; } printf("Test PASSED\n"); return PTS_PASS; }