⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 io.c

📁 最新的libusb库
💻 C
📖 第 1 页 / 共 5 页
字号:
		poll(libusb file descriptors, 120*1000);		if (poll indicates activity)			libusb_handle_events_timeout(ctx, 0);	}	printf("completed!");	// other code here}\endcode * * Here we are <em>serializing</em> completion of an asynchronous event * against a condition - the condition being completion of a specific transfer. * The poll() loop has a long timeout to minimize CPU usage during situations * when nothing is happening (it could reasonably be unlimited). * * If this is the only thread that is polling libusb's file descriptors, there * is no problem: there is no danger that another thread will swallow up the * event that we are interested in. On the other hand, if there is another * thread polling the same descriptors, there is a chance that it will receive * the event that we were interested in. In this situation, <tt>myfunc()</tt> * will only realise that the transfer has completed on the next iteration of * the loop, <em>up to 120 seconds later.</em> Clearly a two-minute delay is * undesirable, and don't even think about using short timeouts to circumvent * this issue! *  * The solution here is to ensure that no two threads are ever polling the * file descriptors at the same time. A naive implementation of this would * impact the capabilities of the library, so libusb offers the scheme * documented below to ensure no loss of functionality. * * Before we go any further, it is worth mentioning that all libusb-wrapped * event handling procedures fully adhere to the scheme documented below. * This includes libusb_handle_events() and all the synchronous I/O functions -  * libusb hides this headache from you. You do not need to worry about any * of these issues if you stick to that level. * * The problem is when we consider the fact that libusb exposes file * descriptors to allow for you to integrate asynchronous USB I/O into * existing main loops, effectively allowing you to do some work behind * libusb's back. If you do take libusb's file descriptors and pass them to * poll()/select() yourself, you need to be aware of the associated issues. * * \section eventlock The events lock * * The first concept to be introduced is the events lock. The events lock * is used to serialize threads that want to handle events, such that only * one thread is handling events at any one time. * * You must take the events lock before polling libusb file descriptors, * using libusb_lock_events(). You must release the lock as soon as you have * aborted your poll()/select() loop, using libusb_unlock_events(). * * \section threadwait Letting other threads do the work for you * * Although the events lock is a critical part of the solution, it is not * enough on it's own. You might wonder if the following is sufficient...\code	libusb_lock_events(ctx);	while (!completed) {		poll(libusb file descriptors, 120*1000);		if (poll indicates activity)			libusb_handle_events_timeout(ctx, 0);	}	libusb_lock_events(ctx);\endcode * ...and the answer is that it is not. This is because the transfer in the * code shown above may take a long time (say 30 seconds) to complete, and * the lock is not released until the transfer is completed. * * Another thread with similar code that wants to do event handling may be * working with a transfer that completes after a few milliseconds. Despite * having such a quick completion time, the other thread cannot check that * status of its transfer until the code above has finished (30 seconds later) * due to contention on the lock. * * To solve this, libusb offers you a mechanism to determine when another * thread is handling events. It also offers a mechanism to block your thread * until the event handling thread has completed an event (and this mechanism * does not involve polling of file descriptors). * * After determining that another thread is currently handling events, you * obtain the <em>event waiters</em> lock using libusb_lock_event_waiters(). * You then re-check that some other thread is still handling events, and if * so, you call libusb_wait_for_event(). * * libusb_wait_for_event() puts your application to sleep until an event * occurs, or until a thread releases the events lock. When either of these * things happen, your thread is woken up, and should re-check the condition * it was waiting on. It should also re-check that another thread is handling * events, and if not, it should start handling events itself. * * This looks like the following, as pseudo-code:\coderetry:if (libusb_try_lock_events(ctx) == 0) {	// we obtained the event lock: do our own event handling	libusb_lock_events(ctx);	while (!completed) {		poll(libusb file descriptors, 120*1000);		if (poll indicates activity)			libusb_handle_events_locked(ctx, 0);	}	libusb_unlock_events(ctx);} else {	// another thread is doing event handling. wait for it to signal us that	// an event has completed	libusb_lock_event_waiters(ctx);	while (!completed) {		// now that we have the event waiters lock, double check that another		// thread is still handling events for us. (it may have ceased handling		// events in the time it took us to reach this point)		if (!libusb_event_handler_active(ctx)) {			// whoever was handling events is no longer doing so, try again			libusb_unlock_event_waiters(ctx);			goto retry;		}			libusb_wait_for_event(ctx);	}	libusb_unlock_event_waiters(ctx);}printf("completed!\n");\endcode * * We have now implemented code which can dynamically handle situations where * nobody is handling events (so we should do it ourselves), and it can also * handle situations where another thread is doing event handling (so we can * piggyback onto them). It is also equipped to handle a combination of * the two, for example, another thread is doing event handling, but for * whatever reason it stops doing so before our condition is met, so we take * over the event handling. * * Three functions were introduced in the above pseudo-code. Their importance * should be apparent from the code shown above. * -# libusb_try_lock_events() is a non-blocking function which attempts *    to acquire the events lock but returns a failure code if it is contended. * -# libusb_handle_events_locked() is a variant of *    libusb_handle_events_timeout() that you can call while holding the *    events lock. libusb_handle_events_timeout() itself implements similar *    logic to the above, so be sure not to call it when you are *    "working behind libusb's back", as is the case here. * -# libusb_event_handler_active() determines if someone is currently *    holding the events lock * * You might be wondering why there is no function to wake up all threads * blocked on libusb_wait_for_event(). This is because libusb can do this * internally: it will wake up all such threads when someone calls * libusb_unlock_events() or when a transfer completes (at the point after its * callback has returned). * * \subsection concl Closing remarks * * The above may seem a little complicated, but hopefully I have made it clear * why such complications are necessary. Also, do not forget that this only * applies to applications that take libusb's file descriptors and integrate * them into their own polling loops. * * You may decide that it is OK for your multi-threaded application to ignore * some of the rules and locks detailed above, because you don't think that * two threads can ever be polling the descriptors at the same time. If that * is the case, then that's good news for you because you don't have to worry. * But be careful here; remember that the synchronous I/O functions do event * handling internally. If you have one thread doing event handling in a loop * (without implementing the rules and locking semantics documented above) * and another trying to send a synchronous USB transfer, you will end up with * two threads monitoring the same descriptors, and the above-described * undesirable behaviour occuring. The solution is for your polling thread to * play by the rules; the synchronous I/O functions do so, and this will result * in them getting along in perfect harmony. * * If you do have a dedicated thread doing event handling, it is perfectly * legal for it to take the event handling lock and never release it. Any * synchronous I/O functions you call from other threads will transparently * fall back to the "event waiters" mechanism detailed above. */void usbi_io_init(struct libusb_context *ctx){	pthread_mutex_init(&ctx->flying_transfers_lock, NULL);	pthread_mutex_init(&ctx->pollfds_lock, NULL);	pthread_mutex_init(&ctx->events_lock, NULL);	pthread_mutex_init(&ctx->event_waiters_lock, NULL);	pthread_cond_init(&ctx->event_waiters_cond, NULL);	list_init(&ctx->flying_transfers);	list_init(&ctx->pollfds);}static int calculate_timeout(struct usbi_transfer *transfer){	int r;	struct timespec current_time;	unsigned int timeout =		__USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;	if (!timeout)		return 0;	r = clock_gettime(CLOCK_MONOTONIC, &current_time);	if (r < 0) {		usbi_err(ITRANSFER_CTX(transfer),			"failed to read monotonic clock, errno=%d", errno);		return r;	}	current_time.tv_sec += timeout / 1000;	current_time.tv_nsec += (timeout % 1000) * 1000000;	if (current_time.tv_nsec > 1000000000) {		current_time.tv_nsec -= 1000000000;		current_time.tv_sec++;	}	TIMESPEC_TO_TIMEVAL(&transfer->timeout, &current_time);	return 0;}static void add_to_flying_list(struct usbi_transfer *transfer){	struct usbi_transfer *cur;	struct timeval *timeout = &transfer->timeout;	struct libusb_context *ctx = ITRANSFER_CTX(transfer);		pthread_mutex_lock(&ctx->flying_transfers_lock);	/* if we have no other flying transfers, start the list with this one */	if (list_empty(&ctx->flying_transfers)) {		list_add(&transfer->list, &ctx->flying_transfers);		goto out;	}	/* if we have infinite timeout, append to end of list */	if (!timerisset(timeout)) {		list_add_tail(&transfer->list, &ctx->flying_transfers);		goto out;	}	/* otherwise, find appropriate place in list */	list_for_each_entry(cur, &ctx->flying_transfers, list) {		/* find first timeout that occurs after the transfer in question */		struct timeval *cur_tv = &cur->timeout;		if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||				(cur_tv->tv_sec == timeout->tv_sec &&					cur_tv->tv_usec > timeout->tv_usec)) {			list_add_tail(&transfer->list, &cur->list);			goto out;		}	}	/* otherwise we need to be inserted at the end */	list_add_tail(&transfer->list, &ctx->flying_transfers);out:	pthread_mutex_unlock(&ctx->flying_transfers_lock);}/** \ingroup asyncio * Allocate a libusb transfer with a specified number of isochronous packet * descriptors. The returned transfer is pre-initialized for you. When the new * transfer is no longer needed, it should be freed with * libusb_free_transfer(). * * Transfers intended for non-isochronous endpoints (e.g. control, bulk, * interrupt) should specify an iso_packets count of zero. * * For transfers intended for isochronous endpoints, specify an appropriate * number of packet descriptors to be allocated as part of the transfer. * The returned transfer is not specially initialized for isochronous I/O; * you are still required to set the * \ref libusb_transfer::num_iso_packets "num_iso_packets" and * \ref libusb_transfer::type "type" fields accordingly. * * It is safe to allocate a transfer with some isochronous packets and then * use it on a non-isochronous endpoint. If you do this, ensure that at time * of submission, num_iso_packets is 0 and that type is set appropriately. * * \param iso_packets number of isochronous packet descriptors to allocate * \returns a newly allocated transfer, or NULL on error */API_EXPORTED struct libusb_transfer *libusb_alloc_transfer(int iso_packets){	size_t os_alloc_size = usbi_backend->transfer_priv_size		+ (usbi_backend->add_iso_packet_size * iso_packets);	int alloc_size = sizeof(struct usbi_transfer)		+ sizeof(struct libusb_transfer)		+ (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)		+ os_alloc_size;	struct usbi_transfer *itransfer = malloc(alloc_size);	if (!itransfer)		return NULL;	memset(itransfer, 0, alloc_size);	itransfer->num_iso_packets = iso_packets;	return __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);}/** \ingroup asyncio * Free a transfer structure. This should be called for all transfers * allocated with libusb_alloc_transfer(). * * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is * non-NULL, this function will also free the transfer buffer using the * standard system memory allocator (e.g. free()). * * It is legal to call this function with a NULL transfer. In this case, * the function will simply return safely. * * \param transfer the transfer to free */API_EXPORTED void libusb_free_transfer(struct libusb_transfer *transfer){	struct usbi_transfer *itransfer;	if (!transfer)		return;	if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)		free(transfer->buffer);	itransfer = __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);	free(itransfer);}/** \ingroup asyncio * Submit a transfer. This function will fire off the USB transfer and then * return immediately. * * It is undefined behaviour to submit a transfer that has already been * submitted but has not yet completed. *

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -