New threading question

This is a discussion on New threading question within the C++ Programming forums, part of the General Programming Boards category; What actually happens when I make a thread and pass a vector reference to it which i fill in the ...

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    215

    New threading question

    What actually happens when I make a thread and pass a vector reference to it which i fill in the thread. example : let say I have a function that takes a vector reference and adds numbers to it. and i thread that function into two threads. is the acces to the passed vector somehow coordinated or is there a possibility ffor two threads to write to the same location in that vector:

    Code:
    void Func(vector<int>& xx){
       for(...)
         xx.push_back(i);
    }
    
    
    void main(){
    
          threads ...
          vec ...
    
           for (int i = 0; i < 2; ++i) 
             threads.push_back(thread(Func, ref(vec)));
    
           for(auto &t : threads)
              t.join();
    }
    will two threads sinc their access and push back or is it up to me to do that ??

    thnx


    PS the above is a form of pseudo-code
    Last edited by baxy; 3 Weeks Ago at 03:46 PM.

  2. #2
    Informer -Adrian's Avatar
    Join Date
    Jan 2013
    Posts
    206
    I'm pretty sure you'll have to avoid trying that, because push_back will result in new allocations and such, which are not designed to be thread safe.

    If the math you do is complex enough (I suspect not), you can have each thread fill its own vector with the computed values and then append these vectors to build your final vector. The appending operation would be protected by a lock:
    Code:
    {
        tempVec.reserve(N);
        for(size_t i = 0; i < N; ++i)
        {
            tempVec[i] = baxyInt;
        }
        std::lock_guard<std::mutex> lock(baxyMutex);
        xx.insert(xx.cend(), tempVec.cbegin(), tempVec.cend());
    }
    Something like the above, I haven't checked for errors. But if you really just want to fill a vector with integers, multiple threads might not be the fastest solution.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Amateur Threading Question
    By ThePermster in forum C# Programming
    Replies: 1
    Last Post: 07-31-2009, 06:27 PM
  2. Threading Question
    By CornyKorn21 in forum C++ Programming
    Replies: 3
    Last Post: 05-30-2008, 11:13 AM
  3. c++ threading
    By Anddos in forum C++ Programming
    Replies: 4
    Last Post: 12-28-2005, 02:29 PM
  4. Threading
    By nc3b in forum C++ Programming
    Replies: 7
    Last Post: 11-18-2005, 01:06 AM
  5. Help with threading
    By crazeinc in forum C Programming
    Replies: 2
    Last Post: 06-02-2005, 05:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21