我有一塊代碼,我在pthread中(讓我們調用這個線程a
),並且我希望產生一個新的pthread(讓我們調用這個線程b
)。主題b
需要傳遞一個deque,我有以下代碼:將deque傳遞給一個新的pthread
void* process_thread_b(void* arg)
{
deque<string> *ptr = (deque<string>*)arg;
cout << "Size -" << ptr->size() << endl;
deque<string>::iterator it;
for(it = ptr->begin(); it != ptr->end(); it++)
{
cout <<(*it) << endl;
}
}
上面的代碼是線程b's
代碼。它通過一個deque並且正確地打印出尺寸。我嘗試打印任何它的元素的那一刻,我得到:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Abort (core dumped)
當我產卵並行線程,我用下面的代碼...
deque<string> myDeque;
// Add strings to deque here...
pthread_t dispatchCommands;
pthread_create(&dispatchCommands, NULL, &process_thread_b, (void*)&myDeque);
底部代碼發生在線程a
。爲什麼當我嘗試打印出deque的一個元素時,出現錯誤,但我可以得到它的大小?
或者確保主服務器不退出當前作用域(或者在線程終止之前不退出該作用域的代理服務器)。 (這兩個更常見的解決方案)。 –
一個很好的習慣用法,當你需要將一個對象傳遞給一個將擁有它的線程時,它將使用'new'分配它,將一個指針傳遞給線程的啓動函數,並讓線程'刪除'它當它完成時。你可以讓線程的啓動函數完成所有的工作,比如:void * MyThreadFunction(void * foo){reinterpret_cast(foo); foo-> RealWorkFunction();刪除foo;返回NULL; }' –
謝謝!這固定它! – user1314238