#Shared list between threads

9 messages · Page 1 of 1 (latest)

languid ravine
#

Hey, I wonder how lists work between threads. For example I want to have a list like std::list<int> numbers
And then on one thread I would have a while loop

while(true)
{
  if(numbers.size() > 0)
  {
      std::cout << list[0];
      list.pop_front();
  }

and then from other threads I would like to add something to that list one in a while, in random moments.
Will that work? Or should I use something else than list?

slender vesselBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

tired flicker
#

You would need to ensure only one thread is doing operation on the list at a time.

karmic silo
#

It's undefined behavior. You're not allowed to read or write a variable when another thread is writing it, unless the type of the variable explicitly says that it's fine (for example some std::mutex and std::atomic<T> operations).

#

Typically you write a wrapper that locks a mutex before accessing list to ensure that only 1 thread can access it at a time.

#

Though your while (true) makes a busy loop, using up a core for nothing. You should probably use a condition variable or semaphore to make the thread sleep until a number is available.

languid ravine
karmic silo
#

Depends on how you implement it. Typically you don't fail, you just wait until whoever else is currently accessing it is done with it.

languid ravine
#

!solved