簡體   English   中英

當訪問/插入值時,增強鏈發布導致分段錯誤

[英]Boost strands post causing segmentation faults when accessing/inserting values

我目前正在編寫一種網絡結構,該結構僅使服務器能夠監聽其自身的結構,非常簡單。 每當調用該鏈來調用一個函數並且該函數從類內調用任何成員時,就會發生分段錯誤。

有一些例外,但值得注意的是,這些分段錯誤發生在

  1. tcp :: acceptor myAcceptor(my_io_service,myEndpoint)
  2. mySockets.insert(...)

現在,我可以輕松地交換myAcceptor並將其放在構造函數的初始化列表中,並將其視為類成員,但是我想避免這種情況。

那么接下來要驗證我的主張呢? 我最近的嘗試是檢查mySockets的大小,我應該注意,它是一個map 調用myStrand.post(...) 之前檢查了大小,並在函數調用中檢查了大小。 這是我注意到的。

mySockets映射大小:

  1. 發布前 :0(未插入任何內容,太好了!)
  2. 在函數調用內,由郵局調用 :999929272(Ughhhh)

似乎有些通風不良,但究竟是什么? 它是否創建了新實例,但是奇怪的是它不是0嗎? 它不能丟失地址,因為這肯定會導致分段錯誤,不是嗎?

這就是我目前在調試過程中的位置。

目標

最終目標是能夠在發布鏈中訪問mySockets和my_io_service。

布局流程

這說明了布局,良好的ol代碼如下

  1. 通過傳遞io_service創建“工作”
  2. 通過調用.run()啟動io_service
  3. 創建TCP服務器
  4. 將參數分配給類成員類型
  5. 調用myStrand.post(...)調用服務器,監聽連接客戶端
  6. 等待客戶端連接等

我選擇了詳細說明問題的代碼示例。

頭文件

using boost::asio::ip::tcp;
bool amIConnected = false;
boost::asio::io_service::strand myStrand;
boost::asio::io_service& my_io_service;
std::map<std::string, std::shared_ptr<tcp::socket>> mySockets;
tcp::acceptor myAcceptor

源文件

ConstructorStuff::ConstructorStuff(boost::asio::io_service& the_service) : 
myStrand(the_service), 
my_io_service(the_service),
myAcceptor(the_service, tcp::endpoint(tcp::v4(), 1337))
{}

void ConstructorStuff::CreateTheServer()
{
    amIConnected = true;
    // std::cout << mySockets.size() << std::endl; Returns 0
    mStrand.post(std::bind(&ConstructorStuff::ListenForConnection, this));
}

void ConstructorStuff::ListenForConection()
{
    // std::cout << mySockets.size() << std::endl; Crazy size
    tcp::acceptor tryAgain(my_io_service, tcp::endpoint(tcp::v4(), 1338)); // Just to showcase the error doesn't just occur through mySockets.
}

在哪里調用ConstructorStuff

void SetupServer()
{
    ConstructorStuff stuff(some_service);
    stuff.CreateTheServer();
}

這調用上面的函數

ServiceStarter spinup(service);
spinup.Start(); // Just queues reference_service.run()
std::shared_ptr<SomeClass> server_interface(new SomeClass ( service ));
server_interface->SetupServer();
boost::this_thread::sleep(boost::posix_time::seconds(20));
server_interface->Cancel(); // Just another function that kills the server.

任何建議都很好!

注意事項

  • 頭文件中放置的myPort之類的其他任何值CreateTheServer()中初始化為1337,然后在ListenForConnection()中調用)的其他值都會突然不同。
  • 為了使任何人都可以放心,可以在分支之外訪問這些值,從而將這個問題鎖定在我遇到的與分支相關的問題上。

編輯

我添加了兩個新的源文件。 我只限於可以顯示的內容,但這足以說明問題。

問題來自於SetupServer ,其中的stuff是局部變量,因此在CreateTheServer之后, stuffmStrand.post(std::bind(&ConstructorStuff::ListenForConnection, this));發布的io_service::run處理程序銷毀了mStrand.post(std::bind(&ConstructorStuff::ListenForConnection, this)); 在刪除的對象上被調用。 然后std::cout << mySockets.size() << std::endl; 打印出奇怪的結果-這是未定義行為的簡單示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM