[英]std::thread causing application to abort with error R6010
我有一個名為Task的類,在內部擁有一個成員std :: thread。 通常的想法是創建一個線程,該線程在處理請求到來時保持活動狀態。
class Task
{
public:
Task();
~Task();
void start();
// some funny stuff here
protected:
Task(const Task& ref);
void main_function();
std::thread m_thread;
// more funny stuff like queues, mutexes, etc
}
在函數start()中,我這樣做:
void Task::start()
{
m_thread = std::thread(std::bind(&Task::main_function, this));
}
問題是該行調用運行時錯誤為R6010的abort()。 我在某處讀到這可能是由於m_thread的析構函數在沒有先前連接的情況下被調用引起的,但是由於線程尚未啟動,因此我無法加入它。
我正在Visual Studio 2012上運行
更新:
因此,我嘗試了一個測試示例,但無法復制該錯誤。 然后我將啟動函數替換為有問題的函數,具體如下:
void Task::start()
{
assert(!m_thread.joinable());
m_thread = std::thread(&Task::main_function,this);
}
但是我仍然收到錯誤R6010。 調用堆棧為:
msvcr110d.dll!_NMSG_WRITE(int rterrnum) Line 226 C
msvcr110d.dll!abort() Line 62 C
msvcr110d.dll!terminate() Line 97 C++
msvcp110d.dll!_Call_func(void * _Data) Line 63 C++
msvcr110d.dll!_callthreadstartex() Line 354 C
msvcr110d.dll!_threadstartex(void * ptd) Line 337 C
UPDATE2:最后可以重現該問題。 代碼如下。 在主函數中調用foo()。
class Task
{
public:
Task() : m_exitFlag(false)
{
std::cout << "constructor called" << std::endl;
}
~Task()
{
m_lock.lock();
m_exitFlag = true;
m_condlock.notify_all();
m_lock.unlock();
if (m_thread.joinable()) m_thread.join();
std::cout << "destructor called" << std::endl;
}
void start()
{
std::cout << "Task start" << std::endl;
assert(!m_thread.joinable());
m_thread = std::thread(&Task::main_function, this);
}
protected:
void main_function()
{
std::cout << "thread started" << std::endl;
while(1)
{
m_lock.lock();
while(m_queue.empty() && !m_exitFlag)
m_condlock.wait(std::unique_lock<std::mutex>(m_lock));
if (m_exitFlag)
{
m_lock.unlock();
std::cout << "thread exiting" << std::endl;
return;
}
std::function<void()> f;
if (!m_queue.empty()) f = m_queue.front();
m_lock.unlock;
if (f != nullptr) f();
}
}
Task(const Task&ref) { }
Task& operator=(const Task& ref) {
return *this;
}
};
void foo() {
Task tk;
tk.start();
}
我猜這里有些比賽條件,因為有時會崩潰,而有些則不會。 一個線程位於〜Task()中的關鍵區域內,另一個線程作為Update1中的堆棧。
切勿直接鎖定互斥鎖。 C ++提供了lock_guard
, unique_lock
等。 因為某種原因。
特別是,此部分存在問題:
m_lock.lock();
while(m_queue.empty() && !m_exitFlag)
m_condlock.wait(std::unique_lock<std::mutex>(m_lock));
新構造的unique_lock
將嘗試鎖定已經鎖定的互斥鎖m_lock
。 如果互斥量是std::mutex
則將導致不確定的行為;如果互斥量是std::recursive_mutex
則可能導致死鎖。 另請注意,當您在調用wait
時將未命名的unique_lock
綁定到非const
引用時 ,此行依賴於非標准的編譯器擴展。
因此,您要做的第一件事就是將鎖命名為變量。 然后,要么將std::adopt_lock
傳遞給鎖的構造函數,要么更好的方法是從不直接鎖住互斥鎖,而總是將其包裝在適當的鎖管理類中。
例如,
m_lock.lock();
m_exitFlag = true;
m_condlock.notify_all();
m_lock.unlock();
變
{
std::lock_guard<std::mutex> lk(m_lock);
m_exitFlag = true;
m_condlock.notify_all();
} // mutex is unlocked automatically as the lock_guard goes out of scope
這樣做還有一個好處,就是如果在關鍵部分拋出異常,您就不會泄漏鎖。
看來您是從隊列的front()中獲取一個函數,然后在解鎖后運行該函數,而無需先使用pop()將其從隊列中刪除。 這是你的意圖嗎? 在這種情況下,下一個隨機線程也可能獲取相同的功能並同時運行。 這些功能是線程安全的嗎? 另外,您檢查queue.empty(),但是執行完函數后,隊列中的空元素在哪里?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.