I am making a websocket++ broadcast server which handles subscription and unsubscription by clients to certain tokens
upon subscribed the client receives continuous updates at an interval of 500ms which I send by reading a shared memory
in the shared memory my server acts as a reader, reading the shared memory and sending the updates to clients
the memory occupied by this server increases and when I reach approx 100 clients with 50 tokens each it ends up occupying around 5gb memory why is this happening
this is the main loop in my code which I believe causes error it is mostly identical to the one given on the websocket++ github repo
void read_shm_and_send_messages() {
// while(true){
int shmid = shmget(1234, 0, 0666);
cout << shmid << endl;
if (shmid == -1) {
perror("shmget");
exit(1);`your text`
}
// Attach the shared memory segment
char *shmaddr = (char *)shmat(shmid, NULL, 0);
if (shmaddr == (char *)-1) {
perror("shmat");
exit(1);
}
struct shmid_ds shmid_ds;
shmctl(shmid, IPC_STAT, &shmid_ds);
int num_integers = shmid_ds.shm_segsz / sizeof(trade_data);
// Allocate the values array dynamically based on the size of shared memory
trade_data *values = new trade_data[num_integers];
std::ofstream file("diff_values2.csv", std::ios::trunc);
// Check if the file is opened successfully
if (!file.is_open()) {
std::cerr << "Error opening file." << std::endl;
return;
}
// Write the header to the CSV file
file << "time takenn";
while(true){
// values = new trade_data[num_integers];
// if(subscription_list.size() == 0){
// clear_shared_memory(shmid);
// }
// Read the stored integer values from the shared memory buffer
// int values[150000];
// memset(values, 0, num_integers * sizeof(trade_data));
for (int i = 0; i < num_integers; ++i) {
memcpy(&values[i], shmaddr + i * sizeof(trade_data), sizeof(trade_data));
}
auto start = std::chrono::steady_clock::now();
int count = 0;
for(auto it:subscription_list){
int token = it;
count += mp[it].size();
send_message_to_connections(token , values[token_index_map[token]]);
}
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
if(!subscription_list.empty()) {
// cout << "Time taken to publish message to all connections : " << std::chrono::duration<double, std::milli>(diff).count() << " ms"<< endl;
file << std::chrono::duration<double, std::milli>(diff).count() << ", " << count << "n";
file.flush();
}
// if(count == 5000){
// system("pkill client_test");
// }
// sleep(2);
// if(subscription_list.size() == 0){
// if (shmdt(shmaddr) == -1) {
// perror("shmdt");
// exit(1);
// }
// break;
// }
// if(count == 500) delete[] values;
usleep(500);
// sleep(2);
}
// delete[] values;
// Detach the shared memory segment
if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(1);
}
}
I expected there to be a constant memory access and not increasing until my program crashed
Ekansh Gupta is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.