MCPcopy Create free account
hub / github.com/apache/brpc / StartWrite

Method StartWrite

src/brpc/socket.cpp:1681–1778  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1679}
1680
1681int Socket::StartWrite(WriteRequest* req, const WriteOptions& opt) {
1682 // Release fence makes sure the thread getting request sees *req
1683 WriteRequest* const prev_head =
1684 _write_head.exchange(req, butil::memory_order_release);
1685 if (prev_head != NULL) {
1686 // Someone is writing to the fd. The KeepWrite thread may spin
1687 // until req->next to be non-UNCONNECTED. This process is not
1688 // lock-free, but the duration is so short(1~2 instructions,
1689 // depending on compiler) that the spin rarely occurs in practice
1690 // (I've not seen any spin in highly contended tests).
1691 req->next = prev_head;
1692 return 0;
1693 }
1694
1695 int saved_errno = 0;
1696 bthread_t th;
1697 bthread_attr_t attr = BTHREAD_ATTR_NORMAL;
1698 bthread_attr_set_name(&attr, "KeepWrite");
1699 SocketUniquePtr ptr_for_keep_write;
1700 ssize_t nw = 0;
1701 int ret = 0;
1702
1703 // We've got the right to write.
1704 req->next = NULL;
1705
1706 // Fast fail when write has been shutdown.
1707 if (_is_write_shutdown) {
1708 goto FAIL_TO_WRITE;
1709 }
1710 _is_write_shutdown = req->need_shutdown_write();
1711
1712 // Connect to remote_side() if not.
1713 ret = ConnectIfNot(opt.abstime, req);
1714 if (ret < 0) {
1715 saved_errno = errno;
1716 SetFailed(errno, "Fail to connect %s directly: %m", description().c_str());
1717 goto FAIL_TO_WRITE;
1718 } else if (ret == 1) {
1719 // We are doing connection. Callback `KeepWriteIfConnected'
1720 // will be called with `req' at any moment after
1721 return 0;
1722 }
1723
1724 // NOTE: Setup() MUST be called after Connect which may call app_connect,
1725 // which is assumed to run before any SocketMessage.AppendAndDestroySelf()
1726 // in some protocols(namely RTMP).
1727 req->Setup(this);
1728
1729 if (opt.write_in_background || ssl_state() != SSL_OFF) {
1730 // Writing into SSL may block the current bthread, always write
1731 // in the background.
1732 goto KEEPWRITE_IN_BACKGROUND;
1733 }
1734
1735 // Write once in the calling thread. If the write is not complete,
1736 // continue it in KeepWrite thread.
1737 if (_conn) {
1738 butil::IOBuf* data_arr[1] = { &req->data };

Callers

nothing calls this directly

Calls 11

bthread_attr_set_nameFunction · 0.85
ssl_stateFunction · 0.85
fdFunction · 0.85
berrorFunction · 0.85
bthread_start_backgroundFunction · 0.85
exchangeMethod · 0.45
c_strMethod · 0.45
SetupMethod · 0.45
CutFromIOBufMethod · 0.45
releaseMethod · 0.45

Tested by

no test coverage detected