atomics have been used for threads stop

This commit is contained in:
brain5lug 2017-10-01 00:46:49 +03:00
parent 8c09a7429c
commit dfa1482ab2
15 changed files with 259 additions and 212 deletions

View file

@ -15,7 +15,7 @@ namespace util
virtual bool init(int argc, char* argv[]);
virtual bool start();
virtual bool stop();
virtual void run () {};
virtual void run () {}
bool isDaemon;
bool running;

View file

@ -942,6 +942,8 @@ namespace http {
}
void HTTPServer::Start ()
{
if (!m_IsRunning.load())
{
bool needAuth; i2p::config::GetOption("http.auth", needAuth);
std::string user; i2p::config::GetOption("http.user", user);
@ -960,15 +962,18 @@ namespace http {
i2p::config::SetOption("http.pass", pass);
LogPrint(eLogInfo, "HTTPServer: password set to ", pass);
}
m_IsRunning = true;
m_IsRunning.store(true);
m_Thread = std::unique_ptr<std::thread>(new std::thread (std::bind (&HTTPServer::Run, this)));
m_Acceptor.listen ();
Accept ();
}
}
void HTTPServer::Stop ()
{
m_IsRunning = false;
if (m_IsRunning.load())
{
m_IsRunning.store(false);
m_Acceptor.close();
m_Service.stop ();
if (m_Thread)
@ -977,10 +982,11 @@ namespace http {
m_Thread = nullptr;
}
}
}
void HTTPServer::Run ()
{
while (m_IsRunning)
while (m_IsRunning.load(std::memory_order_acquire))
{
try
{

View file

@ -8,6 +8,7 @@
#include <thread>
#include <boost/asio.hpp>
#include <sstream>
#include <atomic>
#include "HTTP.h"
namespace i2p
@ -70,7 +71,7 @@ namespace http
private:
bool m_IsRunning;
std::atomic_bool m_IsRunning;
std::unique_ptr<std::thread> m_Thread;
boost::asio::io_service m_Service;
boost::asio::io_service::work m_Work;

View file

@ -101,19 +101,19 @@ namespace client
void I2PControlService::Start ()
{
if (!m_IsRunning)
if (!m_IsRunning.load())
{
Accept ();
m_IsRunning = true;
m_IsRunning.store(true);
m_Thread = new std::thread (std::bind (&I2PControlService::Run, this));
}
}
void I2PControlService::Stop ()
{
if (m_IsRunning)
if (m_IsRunning.load())
{
m_IsRunning = false;
m_IsRunning.store(false);
m_Acceptor.cancel ();
m_Service.stop ();
if (m_Thread)
@ -127,7 +127,7 @@ namespace client
void I2PControlService::Run ()
{
while (m_IsRunning)
while (m_IsRunning.load(std::memory_order_acquire))
{
try {
m_Service.run ();

View file

@ -9,6 +9,7 @@
#include <sstream>
#include <map>
#include <set>
#include <atomic>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/property_tree/ptree.hpp>
@ -101,7 +102,7 @@ namespace client
private:
std::string m_Password;
bool m_IsRunning;
std::atomic_bool m_IsRunning;
std::thread * m_Thread;
boost::asio::io_service m_Service;

View file

@ -28,10 +28,10 @@ namespace transport
void UPnP::Stop ()
{
if (m_IsRunning)
if (m_IsRunning.load())
{
LogPrint(eLogInfo, "UPnP: stopping");
m_IsRunning = false;
m_IsRunning.store(false);
m_Timer.cancel ();
m_Service.stop ();
if (m_Thread)
@ -46,13 +46,16 @@ namespace transport
void UPnP::Start()
{
m_IsRunning = true;
if (!m_IsRunning.load())
{
m_IsRunning.store(true);
LogPrint(eLogInfo, "UPnP: starting");
m_Service.post (std::bind (&UPnP::Discover, this));
std::unique_lock<std::mutex> l(m_StartedMutex);
m_Thread.reset (new std::thread (std::bind (&UPnP::Run, this)));
m_Started.wait_for (l, std::chrono::seconds (5)); // 5 seconds maximum
}
}
UPnP::~UPnP ()
{
@ -61,7 +64,7 @@ namespace transport
void UPnP::Run ()
{
while (m_IsRunning)
while (m_IsRunning.load(std::memory_order_acquire))
{
try
{

View file

@ -7,6 +7,7 @@
#include <condition_variable>
#include <mutex>
#include <memory>
#include <atomic>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
@ -43,7 +44,7 @@ namespace transport
private:
bool m_IsRunning;
std::atomic_bool m_IsRunning;
std::unique_ptr<std::thread> m_Thread;
std::condition_variable m_Started;
std::mutex m_StartedMutex;

View file

@ -10,7 +10,6 @@
namespace i2p {
namespace log {
static Log logger;
/**
* @brief Maps our loglevel to their symbolic name
*/
@ -70,14 +69,18 @@ namespace log {
void Log::Start ()
{
if (!m_IsRunning)
// separate load and store for atomic is valid here
// because only one thread changes m_IsRunning
if (!m_IsRunning.load())
{
m_IsRunning = true;
m_IsRunning.store(true);
m_Thread = new std::thread (std::bind (&Log::Run, this));
}
}
void Log::Stop ()
{
if (m_IsRunning.load())
{
switch (m_Destination)
{
@ -94,7 +97,8 @@ namespace log {
/* do nothing */
break;
}
m_IsRunning = false;
m_IsRunning.store(false);
m_Queue.WakeUp ();
if (m_Thread)
{
@ -103,6 +107,7 @@ namespace log {
m_Thread = nullptr;
}
}
}
void Log::SetLogLevel (const std::string& level) {
if (level == "error") { m_MinLevel = eLogError; }
@ -162,13 +167,13 @@ namespace log {
void Log::Run ()
{
Reopen ();
while (m_IsRunning)
while (m_IsRunning.load(std::memory_order_acquire))
{
std::shared_ptr<LogMsg> msg;
while (msg = m_Queue.Get ())
Process (msg);
if (m_LogStream) m_LogStream->flush();
if (m_IsRunning)
if (m_IsRunning.load(std::memory_order_acquire))
m_Queue.Wait ();
}
}
@ -215,6 +220,7 @@ namespace log {
}
Log & Logger() {
static Log logger;
return logger;
}
} // log

View file

@ -17,6 +17,7 @@
#include <chrono>
#include <memory>
#include <thread>
#include <atomic>
#include "Queue.h"
#ifndef _WIN32
@ -59,7 +60,7 @@ namespace log {
i2p::util::Queue<std::shared_ptr<LogMsg> > m_Queue;
bool m_HasColors;
std::string m_TimeFormat;
volatile bool m_IsRunning;
std::atomic_bool m_IsRunning;
std::thread * m_Thread;
private:
@ -84,8 +85,8 @@ namespace log {
Log ();
~Log ();
LogType GetLogType () { return m_Destination; };
LogLevel GetLogLevel () { return m_MinLevel; };
LogType GetLogType () { return m_Destination; }
LogLevel GetLogLevel () { return m_MinLevel; }
void Start ();
void Stop ();
@ -112,7 +113,7 @@ namespace log {
* @brief Sets format for timestamps in log
* @param format String with timestamp format
*/
void SetTimeFormat (std::string format) { m_TimeFormat = format; };
void SetTimeFormat (std::string format) { m_TimeFormat = format; }
#ifndef _WIN32
/**
@ -146,7 +147,7 @@ namespace log {
LogLevel level; /**< message level */
std::thread::id tid; /**< id of thread that generated message */
LogMsg (LogLevel lvl, std::time_t ts, const std::string & txt): timestamp(ts), text(txt), level(lvl) {};
LogMsg (LogLevel lvl, std::time_t ts, const std::string & txt): timestamp(ts), text(txt), level(lvl) {}
};
Log & Logger();

View file

@ -36,6 +36,10 @@ namespace data
}
void NetDb::Start ()
{
// separate load and store for atomic is valid here
// because only one thread changes m_IsRunning
if (!m_IsRunning.load())
{
m_Storage.SetPlace(i2p::fs::GetDataDir());
m_Storage.Init(i2p::data::GetBase64SubstitutionTable(), 64);
@ -47,13 +51,14 @@ namespace data
if (m_RouterInfos.size () < threshold) // reseed if # of router less than threshold
Reseed ();
m_IsRunning = true;
m_IsRunning.store(true);
m_Thread = new std::thread (std::bind (&NetDb::Run, this));
}
}
void NetDb::Stop ()
{
if (m_IsRunning)
if (m_IsRunning.load())
{
for (auto& it: m_RouterInfos)
it.second->SaveProfile ();
@ -62,11 +67,11 @@ namespace data
m_Floodfills.clear ();
if (m_Thread)
{
m_IsRunning = false;
m_IsRunning.store(false);
m_Queue.WakeUp ();
m_Thread->join ();
delete m_Thread;
m_Thread = 0;
m_Thread = nullptr;
}
m_LeaseSets.clear();
m_Requests.Stop ();
@ -75,8 +80,8 @@ namespace data
void NetDb::Run ()
{
uint32_t lastSave = 0, lastPublish = 0, lastExploratory = 0, lastManageRequest = 0, lastDestinationCleanup = 0;
while (m_IsRunning)
uint64_t lastSave = 0, lastPublish = 0, lastExploratory = 0, lastManageRequest = 0, lastDestinationCleanup = 0;
while (m_IsRunning.load(std::memory_order_acquire))
{
try
{
@ -107,7 +112,9 @@ namespace data
numMsgs++;
}
}
if (!m_IsRunning) break;
if (!m_IsRunning.load(std::memory_order_acquire))
break;
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
if (ts - lastManageRequest >= 15) // manage requests every 15 seconds

View file

@ -8,6 +8,7 @@
#include <string>
#include <thread>
#include <mutex>
#include <atomic>
#include "Base.h"
#include "Gzip.h"
@ -84,12 +85,12 @@ namespace data
void SetHidden(bool hide);
void Reseed ();
Families& GetFamilies () { return m_Families; };
Families& GetFamilies () { return m_Families; }
// for web interface
int GetNumRouters () const { return m_RouterInfos.size (); };
int GetNumFloodfills () const { return m_Floodfills.size (); };
int GetNumLeaseSets () const { return m_LeaseSets.size (); };
int GetNumRouters () const { return m_RouterInfos.size (); }
int GetNumFloodfills () const { return m_Floodfills.size (); }
int GetNumLeaseSets () const { return m_LeaseSets.size (); }
/** visit all lease sets we currently store */
void VisitLeaseSets(LeaseSetVisitor v);
@ -100,7 +101,7 @@ namespace data
/** visit N random router that match using filter, then visit them with a visitor, return number of RouterInfos that were visited */
size_t VisitRandomRouterInfos(RouterInfoFilter f, RouterInfoVisitor v, size_t n);
void ClearRouterInfos () { m_RouterInfos.clear (); };
void ClearRouterInfos () { m_RouterInfos.clear (); }
private:
@ -127,7 +128,7 @@ namespace data
mutable std::mutex m_FloodfillsMutex;
std::list<std::shared_ptr<RouterInfo> > m_Floodfills;
bool m_IsRunning;
std::atomic_bool m_IsRunning;
uint64_t m_LastLoad;
std::thread * m_Thread;
i2p::util::Queue<std::shared_ptr<const I2NPMessage> > m_Queue; // of I2NPDatabaseStoreMsg

View file

@ -445,13 +445,18 @@ namespace tunnel
void Tunnels::Start ()
{
m_IsRunning = true;
if (!m_IsRunning.load())
{
m_IsRunning.store(true);
m_Thread = new std::thread (std::bind (&Tunnels::Run, this));
}
}
void Tunnels::Stop ()
{
m_IsRunning = false;
if (m_IsRunning.load())
{
m_IsRunning.store(false);
m_Queue.WakeUp ();
if (m_Thread)
{
@ -460,13 +465,14 @@ namespace tunnel
m_Thread = 0;
}
}
}
void Tunnels::Run ()
{
std::this_thread::sleep_for (std::chrono::seconds(1)); // wait for other parts are ready
uint64_t lastTs = 0;
while (m_IsRunning)
while (m_IsRunning.load(std::memory_order_acquire))
{
try
{

View file

@ -10,6 +10,7 @@
#include <thread>
#include <mutex>
#include <memory>
#include <atomic>
#include "Queue.h"
#include "Crypto.h"
#include "TunnelConfig.h"
@ -99,20 +100,20 @@ namespace tunnel
std::shared_ptr<const TunnelConfig> GetTunnelConfig () const { return m_Config; }
std::vector<std::shared_ptr<const i2p::data::IdentityEx> > GetPeers () const;
std::vector<std::shared_ptr<const i2p::data::IdentityEx> > GetInvertedPeers () const;
TunnelState GetState () const { return m_State; };
TunnelState GetState () const { return m_State; }
void SetState (TunnelState state);
bool IsEstablished () const { return m_State == eTunnelStateEstablished; };
bool IsFailed () const { return m_State == eTunnelStateFailed; };
bool IsRecreated () const { return m_IsRecreated; };
void SetIsRecreated () { m_IsRecreated = true; };
bool IsEstablished () const { return m_State == eTunnelStateEstablished; }
bool IsFailed () const { return m_State == eTunnelStateFailed; }
bool IsRecreated () const { return m_IsRecreated; }
void SetIsRecreated () { m_IsRecreated = true; }
virtual bool IsInbound() const = 0;
std::shared_ptr<TunnelPool> GetTunnelPool () const { return m_Pool; };
void SetTunnelPool (std::shared_ptr<TunnelPool> pool) { m_Pool = pool; };
std::shared_ptr<TunnelPool> GetTunnelPool () const { return m_Pool; }
void SetTunnelPool (std::shared_ptr<TunnelPool> pool) { m_Pool = pool; }
bool HandleTunnelBuildResponse (uint8_t * msg, size_t len);
virtual void Print (std::stringstream&) const {};
virtual void Print (std::stringstream&) const {}
// implements TunnelBase
void SendTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage> msg);
@ -145,12 +146,12 @@ namespace tunnel
public:
OutboundTunnel (std::shared_ptr<const TunnelConfig> config):
Tunnel (config), m_Gateway (this), m_EndpointIdentHash (config->GetLastIdentHash ()) {};
Tunnel (config), m_Gateway (this), m_EndpointIdentHash (config->GetLastIdentHash ()) {}
void SendTunnelDataMsg (const uint8_t * gwHash, uint32_t gwTunnel, std::shared_ptr<i2p::I2NPMessage> msg);
virtual void SendTunnelDataMsg (const std::vector<TunnelMessageBlock>& msgs); // multiple messages
const i2p::data::IdentHash& GetEndpointIdentHash () const { return m_EndpointIdentHash; };
virtual size_t GetNumSentBytes () const { return m_Gateway.GetNumSentBytes (); };
const i2p::data::IdentHash& GetEndpointIdentHash () const { return m_EndpointIdentHash; }
virtual size_t GetNumSentBytes () const { return m_Gateway.GetNumSentBytes (); }
void Print (std::stringstream& s) const;
// implements TunnelBase
@ -169,14 +170,14 @@ namespace tunnel
{
public:
InboundTunnel (std::shared_ptr<const TunnelConfig> config): Tunnel (config), m_Endpoint (true) {};
InboundTunnel (std::shared_ptr<const TunnelConfig> config): Tunnel (config), m_Endpoint (true) {}
void HandleTunnelDataMsg (std::shared_ptr<const I2NPMessage> msg);
virtual size_t GetNumReceivedBytes () const { return m_Endpoint.GetNumReceivedBytes (); };
virtual size_t GetNumReceivedBytes () const { return m_Endpoint.GetNumReceivedBytes (); }
void Print (std::stringstream& s) const;
bool IsInbound() const { return true; }
// override TunnelBase
void Cleanup () { m_Endpoint.Cleanup (); };
void Cleanup () { m_Endpoint.Cleanup (); }
private:
@ -190,7 +191,7 @@ namespace tunnel
ZeroHopsInboundTunnel ();
void SendTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage> msg);
void Print (std::stringstream& s) const;
size_t GetNumReceivedBytes () const { return m_NumReceivedBytes; };
size_t GetNumReceivedBytes () const { return m_NumReceivedBytes; }
private:
@ -204,7 +205,7 @@ namespace tunnel
ZeroHopsOutboundTunnel ();
void SendTunnelDataMsg (const std::vector<TunnelMessageBlock>& msgs);
void Print (std::stringstream& s) const;
size_t GetNumSentBytes () const { return m_NumSentBytes; };
size_t GetNumSentBytes () const { return m_NumSentBytes; }
private:
@ -224,7 +225,7 @@ namespace tunnel
std::shared_ptr<OutboundTunnel> GetPendingOutboundTunnel (uint32_t replyMsgID);
std::shared_ptr<InboundTunnel> GetNextInboundTunnel ();
std::shared_ptr<OutboundTunnel> GetNextOutboundTunnel ();
std::shared_ptr<TunnelPool> GetExploratoryPool () const { return m_ExploratoryPool; };
std::shared_ptr<TunnelPool> GetExploratoryPool () const { return m_ExploratoryPool; }
std::shared_ptr<TunnelBase> GetTunnel (uint32_t tunnelID);
int GetTransitTunnelsExpirationTimeout ();
void AddTransitTunnel (std::shared_ptr<TransitTunnel> tunnel);
@ -266,7 +267,7 @@ namespace tunnel
private:
bool m_IsRunning;
std::atomic_bool m_IsRunning;
std::thread * m_Thread;
std::map<uint32_t, std::shared_ptr<InboundTunnel> > m_PendingInboundTunnels; // by replyMsgID
std::map<uint32_t, std::shared_ptr<OutboundTunnel> > m_PendingOutboundTunnels; // by replyMsgID
@ -285,15 +286,15 @@ namespace tunnel
public:
// for HTTP only
const decltype(m_OutboundTunnels)& GetOutboundTunnels () const { return m_OutboundTunnels; };
const decltype(m_InboundTunnels)& GetInboundTunnels () const { return m_InboundTunnels; };
const decltype(m_TransitTunnels)& GetTransitTunnels () const { return m_TransitTunnels; };
const decltype(m_OutboundTunnels)& GetOutboundTunnels () const { return m_OutboundTunnels; }
const decltype(m_InboundTunnels)& GetInboundTunnels () const { return m_InboundTunnels; }
const decltype(m_TransitTunnels)& GetTransitTunnels () const { return m_TransitTunnels; }
size_t CountTransitTunnels() const;
size_t CountInboundTunnels() const;
size_t CountOutboundTunnels() const;
int GetQueueSize () { return m_Queue.GetSize (); };
int GetQueueSize () { return m_Queue.GetSize (); }
int GetTunnelCreationSuccessRate () const // in percents
{
int totalNum = m_NumSuccesiveTunnelCreations + m_NumFailedTunnelCreations;

View file

@ -8,6 +8,7 @@
#include "Destination.h"
#include "Streaming.h"
#include <functional>
#include <atomic>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
@ -100,12 +101,14 @@ namespace client
void Start()
{
if(m_Run) return; // already started
if (!m_Run.load())
{
m_Run.store(true);
m_Server.listen(boost::asio::ip::address::from_string(m_Addr), m_Port);
m_Server.start_accept();
m_Run = true;
m_Thread = new std::thread([&] (){
while(m_Run) {
while (m_Run.load(std::memory_order_acquire)) {
try {
m_Server.run();
} catch( std::exception & ex) {
@ -115,14 +118,17 @@ namespace client
});
m_Dest->Start();
}
}
void Stop()
{
if (m_Run.load())
{
for(const auto & conn : m_Conns)
conn->Close();
m_Dest->Stop();
m_Run = false;
m_Run.store(false);
m_Server.stop();
if(m_Thread) {
m_Thread->join();
@ -130,6 +136,7 @@ namespace client
}
m_Thread = nullptr;
}
}
boost::asio::ip::tcp::endpoint GetLocalEndpoint()
{
@ -140,7 +147,7 @@ namespace client
private:
std::vector<WebSocksConn_ptr> m_Conns;
bool m_Run;
std::atomic_bool m_Run;
ServerImpl m_Server;
std::string m_Addr;
int m_Port;

View file

@ -30,7 +30,7 @@ namespace i2p
public:
WebsocketServerImpl(const std::string & addr, int port) :
m_run(false),
m_IsRunning(false),
m_ws_thread(nullptr),
m_ev_thread(nullptr),
m_WebsocketTicker(m_Service)
@ -48,10 +48,12 @@ namespace i2p
}
void Start() {
m_run = true;
if (!m_IsRunning.load())
{
m_IsRunning.store(true);
m_server.start_accept();
m_ws_thread = new std::thread([&] () {
while(m_run) {
while(m_IsRunning.load(std::memory_order_acquire)) {
try {
m_server.run();
} catch (std::exception & e ) {
@ -60,7 +62,7 @@ namespace i2p
}
});
m_ev_thread = new std::thread([&] () {
while(m_run) {
while(m_IsRunning.load(std::memory_order_acquire)) {
try {
m_Service.run();
break;
@ -71,9 +73,12 @@ namespace i2p
});
ScheduleTick();
}
}
void Stop() {
m_run = false;
if (m_IsRunning.load())
{
m_IsRunning.store(false);
m_Service.stop();
m_server.stop();
@ -89,6 +94,7 @@ namespace i2p
}
m_ws_thread = nullptr;
}
}
void ConnOpened(ServerConn c)
{
@ -158,7 +164,7 @@ namespace i2p
private:
typedef std::set<ServerConn, std::owner_less<ServerConn> > ConnList;
bool m_run;
std::atomic_bool m_IsRunning;
std::thread * m_ws_thread;
std::thread * m_ev_thread;
std::mutex m_connsMutex;