I would like in c++ to share a list between two threads. I would like very simple not by taking FIFO or Shared memory so i just use mutex and locks.
I tried this way and its working :
#include <string.h>
#include <mutex>
#include <iostream>
#include <thread>
#include <list>
std::list<int> myList;
std::mutex list_mutex;
void client(){
std::lock_guard<std::mutex> guard(list_mutex);
myList.push_back(4);
};
void server(){
std::lock_guard<std::mutex> guard(list_mutex);
myList.push_back(2);
};
void print(std::list<int> const &list)
{
for (auto const& i: list) {
std::cout << i << "\n";
}
};
int main(int ac, char** av)
{
std::mutex list_mutex;
std::thread t1(client);
std::thread t2(server);
t1.join();
t2.join();
print(myList);
std::cout<<"test";
return 0;
}
And it print me this
24test
This is fine it work HOWEVER i'm not sure i'm using the same lock ? My supervisor wants me to have explicit Lock/Unlock in the code. At least if i can use the same mutex?
Thank you very much to help me