how to use lock in thread?

mc 5,426 Reputation points
2025-06-19T04:31:10.6666667+00:00

I have thread1 and thread3 and both of it will edit the std::queue

how to use lock to it?

both of the thread will edit the std::queue in loop.

Developer technologies C++
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Darran Rowe 1,986 Reputation points
    2025-06-19T13:00:35.32+00:00

    How you do this depends entirely on what you are doing. One really simple case is the following.

    #include <mutex>
    
    static std::mutex s_queue_mutex{};
    
    void thread_proc()
    {
    	//do other thread stuff
    	{
    		std::lock_guard<std::mutex> guard_queue(s_queue_mutex);
    		//modify queue
    		//guard_queue will destruct and unlock the mutex
    	}
    	//do other thread stuff
    }
    

    This creates a global std::mutex that will be used by all threads to protect the queue, and you just use std::lock_guard when you want to protect the queue.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.