lundi 5 janvier 2015

std::thread from c++11 - execute class functions

I have similar question like: enter link description here and: enter link description here


Let me past sample code:



#include <iostream>
#include <cstdint>
#include <thread>
#include <list>

class Item {
public:
void Calculate() {}
void Merge() {}
void Send() {}
};

int main()
{
std::list<Item*> itemlist;
for(uint32_t itemNum = 0 ; itemNum < 100 ; itemNum++)
itemlist.push_back(new Item);

while(true)
{
for(Item *itemOnList : itemlist)
itemOnList->Calculate();

for(Item *itemOnList : itemlist)
itemOnList->Merge();

for(Item *itemOnList : itemlist)
itemOnList->Send();
}

return 0;
}


What i like to do is when program is run all time, for each item in list will be executed in diferent thread.


So for example:



for(Item *itemOnList : itemlist)
itemOnList->Calculate();


Will run on maximum threads (std::thread::hardware_concurrency()), then when that ''Calculate'' function finish i like to call again same threads to do different job ''Merge'', then wait for all of them to finish, and call last one ''Send''.


I was think to do that o list for example:



std::list<Item*> calculateItems;
std::list<Item*> mergeItems;
std::list<Item*> sendItems;


Then create threads and assign ''list'' to make it work, so i will end up with:


3 lists + 8 threads for each list, that will do calculation all time. But problem with this concept is, that i need to finish one 'function' before i can call another.


What i have problem here is how i can manage this functions calls in multithreading way.


Aucun commentaire:

Enregistrer un commentaire