title: Queue In Struct Within Array?
body: <p>I tried to create an application that using multithreads.
  Every worker threads has its own queue to be consumed and processed, while the main thread feeds their queues. The worker threads will be spawned dynamically, according to such conditions.</p>
  
  <p>To maintain information of worker threads for the main thread, each spawned worker thread will be registered to an array:</p>
  
  <pre><code>struct workerNode **workerMap = (workerNode**) malloc(MAX_WORKER * sizeof(struct workerNode));
  </code></pre>
  
  <p>while workerNode is struct injected to each worker threads:</p>
  
  <pre><code>struct workerNode
  {
      int offset;
      queue&lt;dataRecord*&gt; workerQueue;
      short semaphore;
  };
  </code></pre>
  
  <p>The problem is, everytime I try to push a <code>dataRecord*</code> to a worker thread's <code>workerQueue</code>, for more than 1 times, SEGFAULT occurs.
  First push is success, no problem, but the second is totally failure.</p>
  
  <p>This is the gdb backtrace:</p>
  
  <pre><code>Program received signal SIGSEGV, Segmentation fault.
  0x0000000000402382 in __gnu_cxx::new_allocator&lt;int&gt;::construct(int*, int const&amp;) ()
  (gdb) bt
  #0  0x0000000000402382 in __gnu_cxx::new_allocator&lt;int&gt;::construct(int*, int const&amp;) ()
  #1  0x0000000000401e40 in std::deque&lt;int, std::allocator&lt;int&gt; &gt;::push_back(int const&amp;) ()
  #2  0x0000000000401a83 in std::queue&lt;int, std::deque&lt;int, std::allocator&lt;int&gt; &gt; &gt;::push(int const&amp;) ()
  #3  0x0000000000401361 in listenerProcess(int, char*) ()
  #4  0x0000000000401854 in main ()
  </code></pre>
  
  <p>and this is how I call push to the queue:</p>
  
  <pre><code>while(workerMap[index] != 0)
  {
      workerMap[index]-&gt;workerQueue.push(rec);
      index++;
  }
  </code></pre>
  
  <p>Can anyone help me? thanks</p>
  
  <p><strong>EDITED:</strong></p>
  
  <p>As WhozCraig suggested before, I've done another experiment:</p>
  
  <pre><code>struct workerNode **workerMap = (workerNode**) malloc(MAX_WORKER * sizeof(workerNode*)); // storing pointers, not objects
  </code></pre>
  
  <p>I am still using the same way to allocate the <code>workerMap</code>. But I changed the way to register <code>workerNode</code> to the map.</p>
  
  <pre><code>//workerMap[index] = (struct workerNode*) malloc(sizeof(struct workerNode));
  workerMap[index] = new struct workerNode;
  </code></pre>
  
  <p>And the application seems fine now. Thanks :)</p>