Passing a deque to a new pthread

c++, deque, pthreads, thread-safety

Solution

`pthread_create` will return long before your thread function begins to execute. Your `deque` will have been destroyed long ago. You need to create it on the heap.

Problem

I have a block of code where I am inside a pthread (lets call this thread `a`), and I wish to spawn a new pthread (lets call this thread `b`). Thread `b` needs to be passed a deque and I have the following code: ``` 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; } } ``` The above code is thread `b's` code. It is passed a deque and it prints out the size correctly. The moment I try printing out any of it's elements, I get: ``` terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Abort (core dumped) ``` When I am spawning the pthread, I use the below code... ``` deque<string> myDeque; // Add strings to deque here... pthread_t dispatchCommands; pthread_create(&dispatchCommands, NULL, &process_thread_b, (void*)&myDeque); ``` The bottom code takes place in thread `a`. Why is it when I try to print out an element of the deque, I am getting an error, yet I can get it's size?

Original source