将双端队列传递给新的pthread

use*_*238 2 c++ pthreads thread-safety deque

我有一个代码块,我在一个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;
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码是线程b's代码.它传递一个双端队列并正确打印出大小.我尝试打印出任何元素的那一刻,我得到:

terminate called after throwing an instance of 'std::bad_alloc'
 what():  std::bad_alloc
Abort (core dumped)
Run Code Online (Sandbox Code Playgroud)

当我产生pthread时,我使用下面的代码......

 deque<string> myDeque;

 // Add strings to deque here...

 pthread_t dispatchCommands;
 pthread_create(&dispatchCommands, NULL, &process_thread_b, (void*)&myDeque);
Run Code Online (Sandbox Code Playgroud)

底部代码发生在线程中a.为什么当我尝试打印出deque的一个元素时,我收到一个错误,但我可以得到它的大小?

Pup*_*ppy 5

pthread_create在线程函数开始执行之前很久就会返回.你的deque意志很久以前就被摧毁了.您需要在堆上创建它.