【发布时间】:2012-04-30 22:47:06
【问题描述】:
我在 pthread 中有一段代码(让我们将此线程称为 a),并且我希望生成一个新的 pthread(让我们将此线程称为 b)。线程b 需要传递一个双端队列,我有以下代码:
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代码。它传递了一个双端队列并正确打印出大小。当我尝试打印出它的任何元素时,我得到:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Abort (core dumped)
当我生成 pthread 时,我使用下面的代码...
deque<string> myDeque;
// Add strings to deque here...
pthread_t dispatchCommands;
pthread_create(&dispatchCommands, NULL, &process_thread_b, (void*)&myDeque);
底部代码发生在线程a。为什么当我尝试打印出双端队列的一个元素时,我得到一个错误,但我可以得到它的大小?
【问题讨论】:
标签: c++ thread-safety pthreads deque