c++ - How to Create Thread-Safe Buffers / POD? -


my problem quite common suppose, drives me crazy:

i have multi-threaded application 5 threads. 4 of these threads job, network communication , local file system access, , write output data structure of form:

struct buffer {   std::vector<std::string> lines;   bool has_been_modified; } 

the 5th thread prints these buffer/structures screen:

buffer buf1, buf2, buf3, buf4;  ...  if ( buf1.has_been_modified ||       buf2.has_been_modified ||       buf3.has_been_modified ||       buf4.has_been_modified ) {   redraw_screen_from_buffers(); } 

how protect buffers being overwritten while either being read or written to?

i can't find proper solution, although think has quiet common problem.

thanks.

you should use mutex. mutex class std::mutex. c++11 can use std::lock_guard<std::mutex> encapsulate mutex using raii. change buffer struct to

struct buffer {    std::vector<std::string> lines;    bool has_been_modified;    std::mutex mutex; }; 

and whenever read or write buffer or has_been_modified do

std::lock_guard<std::mutex> lockguard(buffer.mutex); //do each buffer want access ... //access buffer here 

and mutex automatically released lock_guard when destroyed.

you can read more mutexes here.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -