Re: [asio-users] Waiting for the data while async_write
Brought to you by:
chris_kohlhoff
From: Benjamin R. <be...@bl...> - 2017-10-23 18:10:39
|
Hi Michael If I were you I would avoid busy-waiting (running a while( !gotPacket) loop to wait) because it tends to keep one entire core busy until it is released. If you need to wait for something, depending on what it is, use std::mutex and similar primitives. Of course, the ideal case would be if you could have everything wrapped inside asynchronous calls, such that no waiting is even necessary and you can just use one thread. The idea of ASIO is that everything 'fires' an event when it's ready, so you never have a thread just waiting. Maybe you could have a flag that is atomically set to true if one of the asynchronous calls fires, and if the second one fires (whichever one it is), the work gets done. Like that, everything is asynchronous. Cheers, Benjamin On 23.10.2017 18:26, Michael IV wrote: > Hi again! I need an advice. I have a situation where the data can be > unavailable when asyn_write is getting called. What's the best > practice to wait for the data in such a case? > Here is the case: > > void Connection::Send() > { > //we write syncrhoniously > MyData packet; > bool gotPacket = task->data_queue.try_dequeue(packet); > if (!gotPacket) > { > // >> ???? // Should I run a while(!gotPacket) here? > } > //fill buffers with data here... > auto self(shared_from_this()); > asio::async_write(mSocket, buffers, > [this, self](const asio::error_code error, size_t bytes_transfered) > { > if (error) > { > std::cout << "Async write interrupted with error:" << error.message() > << std::endl; > return; > } > assert(bytes_transfered); > //chain: > Send(); > } > ); > } > > So should I run a while( !gotPacket) loop to wait for the data to be > available? Or I can somehow skip this async_write without losing > the chaining? Thanks in advance. > > > > > ------------------------------------------------------------------------------ > Check out the vibrant tech community on one of the world's most > engaging tech sites, Slashdot.org! http://sdm.link/slashdot > > > _______________________________________________ > asio-users mailing list > asi...@li... > https://lists.sourceforge.net/lists/listinfo/asio-users > _______________________________________________ > Using Asio? List your project at > http://think-async.com/Asio/WhoIsUsingAsio |