For example, considering there is a character array we add entries from both ends. I want to create a function that given 2 strings, it atomically determines where to insert the two strings in the two ends. I want to use an offset to record the end of the forward direction and an offset to record the end of the backward direction. I wish to modify two variables atomically using fech_add/subtract. One possible way I'm thinking of is to combine the two offsets into 1 64 bits long integer, and combine the two operations into a single atomic operation. The code should look like the following:
atomic<long> combined_offset;
char* array;
long combine_two_lengths(std::string& forward_st, std::string& backward_st){
long size1 = forward_st.length();
long size2 = -1*backward_st.length();
return size1<<32|size2;
}
void append_two_strings(std::string forward_st, std::string backward_st){
long value_to_update = combine_two_lengths(forward_st,backward_st);//combine two string sizes into one 64 bits long
long new_offset = combined_offset.fetch_add(value_to_update);
if(is_still_valid(new_offset))//check the two offsets do not cross
insert_array(array,forward_st,backward_st,new_offset);
else
std::cout<<"Array out of bounds\n";
//enter a critical section and expand the array
}