/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.1*2* Permission is hereby granted, free of charge, to any person obtaining a copy3* of this software and associated documentation files (the "Software"), to4* deal in the Software without restriction, including without limitation the5* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or6* sell copies of the Software, and to permit persons to whom the Software is7* furnished to do so, subject to the following conditions:8*9* The above copyright notice and this permission notice shall be included in10* all copies or substantial portions of the Software.11*12* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR13* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE15* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER16* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING17* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS18* IN THE SOFTWARE.19*/2021#include <assert.h>2223#include "uv.h"24#include "internal.h"25#include "atomicops-inl.h"26#include "handle-inl.h"27#include "req-inl.h"282930void uv__async_endgame(uv_loop_t* loop, uv_async_t* handle) {31if (handle->flags & UV_HANDLE_CLOSING &&32!handle->async_sent) {33assert(!(handle->flags & UV_HANDLE_CLOSED));34uv__handle_close(handle);35}36}373839int uv_async_init(uv_loop_t* loop, uv_async_t* handle, uv_async_cb async_cb) {40uv_req_t* req;4142uv__handle_init(loop, (uv_handle_t*) handle, UV_ASYNC);43handle->async_sent = 0;44handle->async_cb = async_cb;4546req = &handle->async_req;47UV_REQ_INIT(req, UV_WAKEUP);48req->data = handle;4950uv__handle_start(handle);5152return 0;53}545556void uv__async_close(uv_loop_t* loop, uv_async_t* handle) {57if (!((uv_async_t*)handle)->async_sent) {58uv__want_endgame(loop, (uv_handle_t*) handle);59}6061uv__handle_closing(handle);62}636465int uv_async_send(uv_async_t* handle) {66uv_loop_t* loop = handle->loop;6768if (handle->type != UV_ASYNC) {69/* Can't set errno because that's not thread-safe. */70return -1;71}7273/* The user should make sure never to call uv_async_send to a closing or74* closed handle. */75assert(!(handle->flags & UV_HANDLE_CLOSING));7677if (!uv__atomic_exchange_set(&handle->async_sent)) {78POST_COMPLETION_FOR_REQ(loop, &handle->async_req);79}8081return 0;82}838485void uv__process_async_wakeup_req(uv_loop_t* loop, uv_async_t* handle,86uv_req_t* req) {87assert(handle->type == UV_ASYNC);88assert(req->type == UV_WAKEUP);8990handle->async_sent = 0;9192if (handle->flags & UV_HANDLE_CLOSING) {93uv__want_endgame(loop, (uv_handle_t*)handle);94} else if (handle->async_cb != NULL) {95handle->async_cb(handle);96}97}9899100