Reusing thread in loop c++

前端 未结 6 1043
余生分开走
余生分开走 2020-11-29 02:45

I need to parallelize some tasks in a C++ program and am completely new to parallel programming. I\'ve made some progress through internet searches so far, but am a bit stu

6条回答
  •  既然无缘
    2020-11-29 03:39

    Well, it depends if you consider moving a reassigning or not. You can move a thread but not make a copy of it.

    Below code will create new pair of threads each iteration and move them in place of old threads. I imagine this should work, because new thread objects will be temporaries.

    while(user doesn't interrupt)
    {
    //Process first batch of data while acquiring new data
    std::thread proc1(ProcessData,memoryAddress1a);
    std::thread proc2(ProcessData,memoryAddress2a);
    acq1 = std::thread(AcquireData, boardHandle1, memoryAddress1b);
    acq2 = std::thread(AcquireData, boardHandle2, memoryAddress2b);
    acq1.join();
    acq2.join();
    proc1.join();
    proc2.join();
    /*Proceed in this manner, alternating which memory address 
    is written to and being processed until the user interrupts the program.*/
    }
    

    What's going on is, the object actually does not end it's lifetime at the end of the iteration, because it is declared in the outer scope in regard to the loop. But a new object gets created each time and move takes place. I don't see what can be spared (I might be stupid), so I imagine this it's exactly the same as declaring acqs inside the loop and simply reusing the symbol. All in all ... yea, it's about how you classify a create temporary and move.

    Also, this clearly starts a new thread each loop (of course ending the previously assigned thread), it doesn't make a thread wait for new data and magically feed it to the processing pipe. You would need to implement it a differently like. E.g: Worker threads pool and communication over queues.

    References: operator=, (ctor).

    I think the errors you get are self-explanatory, so I'll skip explaining them.

提交回复
热议问题