c++multithreadingmutexlocks

List share between two threads


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


Solution

  • Ted's comment is important, what you are working with are threads, not processes. Processes don't share memory (besides using Shared Memory, but you wanted to avoid that). Threads share their entire memory space with each other.

    You also mentioned that your supervisor wants you to use unlock/lock sections. You could do this by calling:

    list_mutex.lock()
    ... critical section ...
    list_mutx.unlock()
    

    But you already do this implicitly by constructing a lock_guard. The lock_guard locks when you create it and unlocks at the end of the current scope.

    As noted by Ted, you need to remove the second declaration of list_mutex (inside main).