为什么std :: queue.front()导致段错误?

时间:2017-02-06 16:48:48

标签: c++ multithreading stl memcached threadpool

这是场景: 我正在尝试使用libev编写一个简单的多线程服务器,并实现memcached使用的线程池模型,它使用调度程序线程和几个工作线程(但问题不是关于libev或memcached)。

我定义了一个类program Tests; uses Spring.Testing, TestInsight.DUnit; type TUrlTests = class(TTestCase) public class function UrlProvider: TArray<string>; static; published [TestCaseSource('UrlProvider')] procedure TestUrl(const url: string); end; { TUrlTests } procedure TUrlTests.TestUrl(const url: string); begin // do whatever end; class function TUrlTests.UrlProvider: TArray<string>; begin Result := ['https://helloacm.com', 'https://codingforspeed.com']; end; begin TUrlTests.Register; RunRegisteredTests; end. ,就像

一样
WorkerThreadPool

和WorkerThread是下面的结构(省略一些不必要的字段)

class WorkerThreadPool 
{
//...
private:
    WorkerThread *worker_threads; //worker threads, enough space allocated
};

然后在类typedef struct { thread_t tid; std::queue<event_entry *> event_queue; //event_entry is irrelavant here }WorkerThread; 中有一个私有静态成员函数eventHandler,其中我访问其中一个线程结构(所有线程都已成功创建),如下

WorkerThreadPool

然而,它在“非空。\ n”输出后立即崩溃,因为它没有打印“罚款。\ n”。

起初我认为这是因为静态成员函数无法访问非静态成员,但当我将WorkerThread *wthread = &worker_threads[0]; if(whtread->event_queue.empty()){ std::cout << "Empty!\n"; }else{ std::cout << "Not empty.\n"; event_entry *evt = wthread->event_queue.front(); std::cout << "fine.\n"; } 更改为静态时,错误仍然是。我也试图将worker_threads修改为公开,但没有运气。

现在我真的很困惑,我已经被困了好几天了。有人能给我一些帮助吗?

1 个答案:

答案 0 :(得分:1)

event_entry *evt = wthread->event_queue.front();
队列为空时

是一个问题。

您需要使用:

WorkerThread *wthread = &worker_threads[0];
if(whtread->event_queue.empty())
{
    std::cout << "Empty!\n";
}
else
{
    std::cout << "Not empty.\n";
    event_entry *evt = wthread->event_queue.front();
}
std::cout << "fine.\n";