boost::threads example and heap corruption message - c++

I'm quite new to boost::threads, I read the documentation and but i'm having some trouble applying it in practice, perhaps you can help? First of all, I have taken the time to write a self contained code listing that demonstrates 2 types of behavior that I cannot yet understand...
The program allows the user to issue 3 different commands,
task [name]
info
quit
The purpose is that task will launch some work on a new thread, but then return back to the command prompt while the work is carried out. The user can give the info command to find out which tasks have completed and which have not.
Im using a dual core Win7 machine and Visual Studio 2008 Express.
Problem 1>
Issuing the command, task p1 p2 p3, starts 3 tasks running. This can be checked by issuing info. After a few seconds the work is complete, however for some reason the completed flag is not always set true on 1 or 2 of the tasks.
Problem 2>
Quiting the program then produces the following message:
Windows has triggered a breakpoint in example.exe. This may be due to a corruption of the heap, which indicates a bug in example.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while example.exe has focus.
The output window may have more diagnostic information.
Hopefully you can reproduce this behavior and help.
Thanks in advance.
Alex.
//WARNING: THIS CODE DOES NOT BEHAVE EXACTLY AS INTENDED
#include <iostream>
#include <string>
#include <sstream>
#include <boost/thread.hpp>
using namespace std;
class task {
public:
string mname;
bool completed;
void start()
{
int a = 0;
for (int i=0 ; i<10000; i++)
{
for (int j=0 ; j<100000; j++)
{
a= i*2;
}
}
this->completed = true;
}
task(string name)
{
mname = name;
completed = false;
}
};
class taskManager{
public:
boost::thread_group threads;
void startTask( string name )
{
//add new task to vector list
mtasks.push_back( task(name) );
// execute start() on a new thread
threads.create_thread( boost::bind( &task::start, &mtasks.back()) );
}
int tasksTotal()
{
return mtasks.size();
}
string taskInfo(int i)
{
string compstr("Not Completed");
if ( mtasks[i].completed == true )
{
compstr = "Completed";
}
return mtasks[i].mname + " " + compstr;
}
private:
vector<task> mtasks;
};
int main(int argc, char* argv[])
{
string cmd, temp;
stringstream os;
bool quit = false;
taskManager mm;
cout << "PROMPT>";
while (quit == false)
{
//Wait for a valid command from user
getline(cin,cmd);
// Reset stringstream and assign new cmd string
os.clear();
os << "";
os << cmd;
//parse input string
while (os >> temp)
{
if ( temp.compare("task") == 0 )
{
while (os >> temp) { mm.startTask( temp ); }
}
if ( temp.compare("info") == 0 )
{
// Returns a list of all completed and not completed tasks
for (int i = 0; i<mm.tasksTotal(); i++)
{
cout << mm.taskInfo(i).c_str() << endl;
}
}
if ( temp.compare("quit") == 0 ){ quit = true; }
}
cout << "PROMPT>";
}
mm.threads.join_all();
return 0;
};

There is a problem with your code in the taskManager::startTask method:
mtasks.push_back( task(name) );
// execute start() on a new thread
threads.create_thread( boost::bind( &task::start, &mtasks.back())
The problem here is that on pushing back a new task, your vector might have to reallocate some space and such invalidate the references to your old vector elements, such the following calls to taskinfo will reference to the wrong elements. As you delete the old elements your heap will somehow get corrupted.
An easy fix would be to reserve some space for the vector in the constructor of your taskManager class, however you should probably change the design of your task/taskmanager model instead. Another way would be to use a std::deque, as that one won't reallocate memory.

Related

stopping a while / for loop when an user says so

i'm new to c++ so I only kind of know iostream and the syntax of the language.
I am writing a program that creates an infinite amount of .txt files using fstream but i'm kind of stuck, I want it to have a menu in the program so the user could interfere with the process with the help of commands I will code in void functions("pause", "stop", etc...)
It means that the process of creating .txt files should run constantly but that the user could also write in a cin>> the keywords shown above to interfere with the process
I plan to write multiple commands so I'll surely use switch statement in the future but to show you my problem I'll only use a while loop with one command
So I've tried things like that:
void stop()
{
return 0;
}
int main()
{
string command= "";
int i=1;
if (command!="stop")
{
while (i<=2)
{
CreateNewFile();
cin >> command;
}
} else
{
stop();
}
}
But the problem with this kind of loop is that it asks the user to write something everytime in order to reset the loop and it is this thing in particular that I want to avoid...
I want to keep the loop running as long as my user wants it to
I'm sure that the answer is really simple but i've not found any help by asking google so i'll tr to ask you guys.
Thank you in advance to those who will take the time to asnwer me
My advise, Adam, is to change your problem description so you ask user how many files they want to create, and then run the loop that many times:
for(;;) {
unsigned n;
cout << "How many files do you want to create (0 to stop)? ";
cin >> n;
if(!n) break;
for(unsigned i = 0; i < n; i++) {
CreateNewFile();
}
}
I had something on this line wherein the thread that's doing the actual work continues and only processes commands if the user wants to.
#include <iostream>
#include <string>
#include <thread>
#include <stack>
#include <chrono>
#include <mutex>
int main() {
std::stack<std::string> commandQueue;
std::mutex m;
int i = 0;
std::thread worker([&]() {
bool suspend = false;
while(true) {
{
const std::lock_guard<std::mutex> lock(m);
if(!commandQueue.empty()){
std::string command = commandQueue.top();
commandQueue.pop();
if(command == "continue"){
suspend = false;
//process continue
} else if (command == "pause"){
suspend = true;
//process other commands....
} else if(command == "stop") {
//process stop
return; //exit thread
}
}
}
//Commands processed, continue as usual
if(!suspend) {//Process only if not paused
using namespace std::chrono_literals;
//Continue creating files or whatever it is that needs to be done continuously
std::this_thread::sleep_for(500ms);
i++;
//std::cout<<"Value of i is "<<i<<'\n';
//CreatFileName();
}
}
});
std::string command;
do {
std::cout<<"Enter commands to interact\n";
std::cin>>command;
{
const std::lock_guard<std::mutex> lock(m);
commandQueue.push(command);
}
}while(command != "stop");
worker.join();
std::cout<<"After execution, value of i is "<<i<<'\n';
}
Of course, the output of this specific example is a bit ugly because it is printing to the console from 2 different threads but the commands like stop, pause, continue are processed fine since there's only one thread (the main thread) that reads in the commands but since this is just to demonstrate how one can possibly achieve what you intend to, I didn't spend up too much time on the output aesthetics.
So after a while this is basically the simplest solution:
#include <iostream>
#include <thread>
#include <string>
static bool finished = false;
void createFile() {
while (!finished) {
//Your code
}
}
int main() {
std::string answer;
std::thread question(createFile);
std::cin >> answer;
if (answer == "stop") {
finished = true;
}
question.join();
return 0;
}
Here we create a thread which will keep running until they type stop. I ran the code and it was working I made it print out 1 until I wrote stop.

How to run an infinite loop?

I want to run some code over and over again basically forever, but I don't want my computer to run out of memory or something like that. So I was wondering how i could do that in c++? I did this.
for (int i = 0; i <= 2; i++) {
if (i == 1) {i = 0;}
//My code here
}
I was wondering if this would do something bad to my computer?
while(true)
{
//Your code here
}
If you prefer the for syntax:
for ( ; ; ) {
// do stuff.
}
An infinite loop will not cause your computer to run out of memory if you aren't allocating memory without freeing them.
There are a few common ways of writing an infinite loop.
for (;;) {
// do something over an over again
}
while (true) {
// do something over an over again
}
By itself, an infinite loop doesn't cause the program to run out of memory. But if you allocate memory and forget to deallocate it, that would cause memory leak. In light that, the following code would be alright:
YourClass* p;
for (;;) {
p = new YourClass(); // every time the loop runs, a new instance of the class is created
// [do something useful with the object]
delete p; // clean-up: deallocate the object.
}
But this would cause a memory leak:
YourClass* p;
for (;;) {
p = new YourClass(); // every time the loop runs, a new instance of the class is created
// [do something useful with the object]
// oups... forgot to deallocate the object.
}
Infinite Loops are great if you know how to manage them. Even with an infinite loop you would still want a possible exit condition. If you are designing infinite loops as to where there are no possible exits out of the loop based on its dataset, the safest thing to do is to keep track of the instance of your application object and its current state and when its state changes to exit, then any infinite loop running across any thread can be tested against this and will automatically exit when available to do so to prevent your computer from hanging to where you would need to do a hard reset or shutdown. Just make sure that all of your memory will be cleaned up as this event is triggered. Now if you have multiple threads running either in parallel or asynchronous and they are managed by a queue or event trigger list then it still may take time for every loop to exit depending on which loops you designate to be in a CRITICAL_SECTION.
class Application {
public:
enum ApplicationState {
APPLICATION_RUNNING = 0,
APPLICATION_PAUSED, // Out of Focus or Paused If In A Timed Situation
APPLICATION_EXIT,
};
private:
// Member Variables Such As Window Handle, Time Etc.,
ApplicationState m_state;
public:
Application();
// virtual ~Application(); // Default Okay - Use Virtual If Using Inheritance
ApplicationState getState() const { return m_state; }
bool start() { m_sate = APPLICATION_RUNNING; return true; }
bool pause() { m_state = APPLICATION_PAUSED; return true; }
// resume may keep track of time if the application uses a timer.
// This is what makes it different than start() where the timer
// in start() would be initialized to 0. And the last time before
// paused was trigger would be saved, and then reset as new starting
// time for your timer or counter.
bool resume() { m_state = APPLICATION_RUNNING; return true; }
bool exit(); { m_state = APPLICATION_EXIT; return false; }
};
int main() {
Application app;
app.start();
// One Type Of Infinite Loop, with a safety net.
while ( !app.exit() ) {
// do some work
}
// Another Type Similar But Different
while ( app.getState() == Application::APPLICATION_RUNNING ) {
// do some work
}
// A Third Type
while ( true ) {
switch( app.getState() ) {
case Application::APPLICATION_RUNNING {
app.start(); // If Not Done Above Outside of Loop
// Do Some Work
break;
}
case Application::APPLICATION_PAUSE {
// Wait Till You Has Focus Or Continues
break;
}
case Application::APPLICATION_EXIT {
// Change The Application State
app.pause();
break;
}
default: {
// ErrorHandling Throw An Exception Etc.
}
} // switch
} while
return 0;
}
Some Of These Types of methods you may not necessarily see in the main.cpp.
You would see these types of loops within your application class that are done privately and invoked publicly so that your main.cpp would look cleaner as such:
main.cpp
#include "Application.h"
int main() {
try {
// Initialize Loggers, Settings, Process - Thread Blockers etc.
// Handle Input Arguements
// Give The Main Thread Application, Window Handle, Mutex etc, A Unique Name
const std::string strApplicationName( "My Application" );
Application app( strApplicationName );
app.start();
}
} catch( YourTypes& e ) {
// Print Errors To Either File Or Console
return RETURN_ERROR;
} catch ( ... ) { // Default Types
// Print Errors To Either File Or Console
return RETURN_ERROR;
}
return RETURN_OK; // return 0;
}
This way your main is clean and easy to follow and your loops are happening within your application class object. This way you can still have infinite loops running as long as the application is running. Now if you are writing drivers, file or memory monitors, malware or antivirus dlls or processes that run in windows background then you may not want this behavior, but since these processes run in the background of windows it is still safe to say yes if this process or executable goes out of scope and ends we still want to exit all loops safely and clean up all memory!
The Paradigm here is to safely and efficiently manage a well structured application. The reason I used this as an example is that when you get away from writing event driven or data driven types of applications and are working with any kind of game development this is an appropriate model to follow. The only difference instead of naming your class as Application, you would more than likely name it Game and have Game inherit from an Engine class. This way the code is re-usable to build and develop multiple games. It is generic enough to handle all graphics, sounds, fonts, rendering etc., and this Engine class will be abstract where this base class can not be instantiated on its own, you would have to create the Game class object as an inherited class that can be instantiated. You may also want to have the Engine class inherit from a Singleton class so that you can only ever have one instance of a Game : Engine object. The Game class would then be responsible for all of the assets being loaded, level designs being loaded, which fonts & sounds to be loaded, which animations to load, etc., things that are unique to this game. This makes it very modular. This setup would also require the Engine to construct multiple Manager type classes that rely heavily on templates.
This following is not my work, but is a project I've been working on and all credit goes to Marek A. Krzeminski, MASc at http://www.marekknows.com This excerpt shows the main.cpp file.
// Version: 1.0
// Copyright (c) 2012 by Marek A. Krzeminski, MASc
// Marek#MarekKnows.com
#include "stdafx.h"
#include "BuildConfig.h"
#include "Settings.h"
#include "BlockProcess.h"
#include "Logger.h"
#include "Utility.h"
#include "Game.h"
// ----------------------------------------------------------------------------
// _tmain()
// Main Entry Point Into Application
int _tmain( int iNumArguments, _TCHAR* pArgumentText[] ) {
using namespace vmk;
try {
// Test If Engine Is Supported By This Compiler
Utility::testPlatform();
Logger logger( "logger.txt" );
Settings settings;
// Prevent Starting Game Multiple Times At Once
BlockProcess processBlocker( settings.getNameAndVersion() );
if ( processBlocker.isBlocked() ) {
std::ostringstream strStream;
strStream << settings.getNameAndVersion() << " is already running in another window" << std::endl;
throw ExceptionHandler( strStream, false );
}
// Handle Input Arguments
bool bShowHelp = false;
for ( int i = 1; i < iNumArguments; ++i ) {
std::ostringstream strStream;
strStream << "Input Argument " << i << ": " << pArgumentText[i];
std::string strArgument( Utility::toLower( std::string( pArgumentText[i] ) ) );
if ( strArgument.compare( "/?" ) == 0 || strArgument.compare( "help" ) == 0 ) {
bShowHelp = true;
} else if ( strArgument.compare( "window" ) == 0 ) {
settings.setWindowDisplayMode( true );
} else if ( strArgument.compare( "debug_memory" ) == 0 ) {
settings.setDebugLogging( settings.getDebugLogging() | Settings::DEBUG_MEMORY );
} else if ( strArgument.compare( "seed" ) == 0 ) {
// Need Next Argument To Know Which Seed Value To Use
bool bError = false;
unsigned uSeedValue = 0;
if ( i + 1 < iNumArguments ) {
uSeedValue = Utility::convertToUnsigned( std::string( pArgumentText[i+1] ) );
if ( uSeedValue == 0 ) {
bError = true;
} else {
settings.setRandomNumberSeed( uSeedValue );
i++; // Move Argument Counter Past Seed Value
}
} else {
bError = true;
}
if ( bError ) {
// Missing Argument For Seed Value
std::cout << " <- Missing Seed Value After This Argument";
} else {
// Display Seed Value To Use
strStream << " " << uSeedValue;
}
} else {
strStream << " <- Unrecognized input argument";
}
Logger::log( strStream, Logger::TYPE_CONSOLE );
}
if ( bShowHelp ) {
std::ostringstream strStream;
strStream << std::endl
<< settings.getNameAndVersion() << " command line arguments:" << std::endl
<< " seed nnn | Supply seed value (nnn) to use in random number generator" << std::endl
<< " window | Run the program in a window rather then full screen" << std::endl
<< " debug_memory | Log extra messages when objects are allocated in memory" << std::endl
<< std::endl;
Logger::log( strStream, Logger::TYPE_CONSOLE );
} else {
// Run The Game Here
Game game;
game.start();
}
} catch( ExceptionHandler& e ) {
std::cout << "Exception Thrown: " << e.getMessage() << std::endl;
Utility::pressAnyKeyToQuit();
return RETURN_ERROR;
} catch( ... ) {
std::cout << __FUNCTION__ << " Caught Unknown Exception" << std::endl;
Utility::pressAnyKeyToQuit();
return RETURN_ERROR;
}
return RETURN_OK;
} // _tmain
As you can see there is no visible infinite while or for loop visible here since this type of algorithm is nested deep within the Game - Engine object.

How to apply a concurrent solution to a Producer-Consumer like situation

I have a XML file with a sequence of nodes. Each node represents an element that I need to parse and add in a sorted list (the order must be the same of the nodes found in the file).
At the moment I am using a sequential solution:
struct Graphic
{
bool parse()
{
// parsing...
return parse_outcome;
}
};
vector<unique_ptr<Graphic>> graphics;
void producer()
{
for (size_t i = 0; i < N_GRAPHICS; i++)
{
auto g = new Graphic();
if (g->parse())
graphics.emplace_back(g);
else
delete g;
}
}
So, only if the graphic (that actually is an instance of a class derived from Graphic, a Line, a Rectangle and so on, that is why the new) can be properly parse, it will be added to my data structure.
Since I only care about the order in which thes graphics are added to my list, I though to call the parse method asynchronously, such that the producer has the task of read each node from the file and add this graphic to the data structure, while the consumer has the task of parse each graphic whenever a new graphic is ready to be parsed.
Now I have several consumer threads (created in the main) and my code looks like the following:
queue<pair<Graphic*, size_t>> q;
mutex m;
atomic<size_t> n_elements;
void producer()
{
for (size_t i = 0; i < N_GRAPHICS; i++)
{
auto g = new Graphic();
graphics.emplace_back(g);
q.emplace(make_pair(g, i));
}
n_elements = graphics.size();
}
void consumer()
{
pair<Graphic*, size_t> item;
while (true)
{
{
std::unique_lock<std::mutex> lk(m);
if (n_elements == 0)
return;
n_elements--;
item = q.front();
q.pop();
}
if (!item.first->parse())
{
// here I should remove the item from the vector
assert(graphics[item.second].get() == item.first);
delete item.first;
graphics[item.second] = nullptr;
}
}
}
I run the producer first of all in my main, so that when the first consumer starts the queue is already completely full.
int main()
{
producer();
vector<thread> threads;
for (auto i = 0; i < N_THREADS; i++)
threads.emplace_back(consumer);
for (auto& t : threads)
t.join();
return 0;
}
The concurrent version seems to be at least twice as faster as the original one.
The full code has been uploaded here.
Now I am wondering:
Are there any (synchronization) errors in my code?
Is there a way to achieve the same result faster (or better)?
Also, I noticed that on my computer I get the best result (in terms of elapsed time) if I set the number of thread equals to 8. More (or less) threads give me worst results. Why?
Blockquote
There isn't synchronization errors, but I think that the memory managing could be better, since your code leaked if parse() throws an exception.
There isn't synchronization errors, but I think that your memory managing could be better, since you will have leaks if parse() throw an exception.
Blockquote
Is there a way to achieve the same result faster (or better)?
Probably. You could use a simple implementation of a thread pool and a lambda that do the parse() for you.
The code below illustrate this approach. I use the threadpool implementation
here
#include <iostream>
#include <stdexcept>
#include <vector>
#include <memory>
#include <chrono>
#include <utility>
#include <cassert>
#include <ThreadPool.h>
using namespace std;
using namespace std::chrono;
#define N_GRAPHICS (1000*1000*1)
#define N_THREADS 8
struct Graphic;
using GPtr = std::unique_ptr<Graphic>;
static vector<GPtr> graphics;
struct Graphic
{
Graphic()
: status(false)
{
}
bool parse()
{
// waste time
try
{
throw runtime_error("");
}
catch (runtime_error)
{
}
status = true;
//return false;
return true;
}
bool status;
};
int main()
{
auto start = system_clock::now();
auto producer_unit = []()-> GPtr {
std::unique_ptr<Graphic> g(new Graphic);
if(!g->parse()){
g.reset(); // if g don't parse, return nullptr
}
return g;
};
using ResultPool = std::vector<std::future<GPtr>>;
ResultPool results;
// ThreadPool pool(thread::hardware_concurrency());
ThreadPool pool(N_THREADS);
for(int i = 0; i <N_GRAPHICS; ++i){
// Running async task
results.emplace_back(pool.enqueue(producer_unit));
}
for(auto &t : results){
auto value = t.get();
if(value){
graphics.emplace_back(std::move(value));
}
}
auto duration = duration_cast<milliseconds>(system_clock::now() - start);
cout << "Elapsed: " << duration.count() << endl;
for (size_t i = 0; i < graphics.size(); i++)
{
if (!graphics[i]->status)
{
cerr << "Assertion failed! (" << i << ")" << endl;
break;
}
}
cin.get();
return 0;
}
It is a bit faster (1s) on my machine, more readable, and removes the necessity of shared datas (synchronization is evil, avoid it or hide it in a reliable and efficient way).

Making threads redo a print function in order

This is a home assignment.
Have to print a string(given as input) in small chunks(Size given as input) by multiple threads one at a time in order 1,2,3,1,2,3,1,2(number of threads is given as input).
A thread does this printing function on creation and I want it to redo it after all the other threads. I face two problems:
1. Threads don't print in fixed order(mine gave 1,3,2,4 see output)
2. Threads need to re print till the entire string is exhausted.
This is what I tried...
#include<iostream>
#include<mutex>
#include<thread>
#include<string>
#include<vector>
#include<condition_variable>
#include<chrono>
using namespace std;
class circularPrint{
public:
int pos;
string message;
int nCharsPerPrint;
mutex mu;
condition_variable cv;
circularPrint(){
pos=0;
}
void shared_print(int threadID){
unique_lock<mutex> locker(mu);
if(pos+nCharsPerPrint<message.size())
cout<<"Thread"<<threadID<<" : "<<message.substr(pos,nCharsPerPrint)<<endl;
else if(pos<message.size())
cout<<"Thread"<<threadID<<" : "<<message.substr(pos)<<endl;
pos+=nCharsPerPrint;
}
};
void f(circularPrint &obj,int threadID){
obj.shared_print(threadID);
}
int main(){
circularPrint obj;
cout<<"\nMessage : ";
cin>>obj.message;
cout<<"\nChars : ";
cin>>obj.nCharsPerPrint;
int nthreads;
cout<<"\nThreads : ";
cin>>nthreads;
vector<thread> threads;
for(int count=1;count<=nthreads;++count)
{
threads.push_back(thread(f,ref(obj),count));
}
for(int count=0;count<nthreads;++count)
{
if(threads[count].joinable())
threads[count].join();
}
return 0;
}
Why would you want to multithread a method that can only be executed once at a time?
Anyway, something like this below? Be aware that the take and print use different locks and that there is a chance the output does not show in the expected order (hence, the why question above).
#include <iostream>
#include <mutex>
#include <thread>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class circularPrint
{
public:
int pos;
string message;
int nCharsPerPrint;
mutex takeLock;
mutex printLock;
circularPrint() {
pos = 0;
}
string take(int count) {
lock_guard<mutex> locker(takeLock);
count = std::min(count, (int)message.size() - pos);
string substring = message.substr(pos, count);
pos += count;
return substring;
}
void print(int threadID, string& message) {
lock_guard<mutex> locker(printLock);
cout << "Thread" << threadID << " : " << message << endl;
}
void loop(int threadID) {
string message;
while((message = take(nCharsPerPrint)).size() > 0) {
print(threadID, message);
}
}
};
void f(circularPrint &obj, int threadID)
{
obj.loop(threadID);
}
int main()
{
circularPrint obj;
//cout << "\nMessage : ";
//cin >> obj.message;
//cout << "\nChars : ";
//cin >> obj.nCharsPerPrint;
int nthreads;
//cout << "\nThreads : ";
//cin >> nthreads;
nthreads = 4;
obj.message = "123456789012345";
obj.nCharsPerPrint = 2;
vector<thread> threads;
for (int count = 1; count <= nthreads; ++count)
threads.push_back(thread(f, ref(obj), count));
for (int count = 0; count < nthreads; ++count) {
if (threads[count].joinable())
threads[count].join();
}
return 0;
}
Currently each thread exits after printing one message - but you need more messages than threads, so each thread will need to do more than one message.
How about putting an infinite loop around your current locked section, and breaking out when there are no characters left to print?
(You may then find that the first thread does all the work; you can hack that by putting a zero-length sleep outside the locked section, or by making all the threads wait for some single signal to start, or just live with it.)
EDIT: Hadn't properly realised that you wanted to assign work to specific threads (which is normally a really bad idea). But if each thread knows its ID, and how many there are, it can figure out which characters it is supposed to print. Then all it has to do is wait till all the preceding characters have been printed (which it can tell using pos), do its work, then repeat until it has no work left to do and exit.
The only tricky bit is waiting for the preceding work to finish. You can do that with a busy wait (bad), a busy wait with a sleep in it (also bad), or a condition variable (better).
You need inter thread synchronization, each thread doing a loop "print, send a message to next one, wait for a message (from the last thread)".
You can use semaphores, events, messages or something similar.
Something as:
#include <string>
#include <iostream>
#include <condition_variable>
#include <thread>
#include <unistd.h>
using namespace std;
// Parameters passed to a thread.
struct ThreadParameters {
string message; // to print.
volatile bool *exit; // set when the thread should exit.
condition_variable* input; // condition to wait before printing.
condition_variable* output; // condition to set after printing.
};
class CircularPrint {
public:
CircularPrint(int nb_threads) {
nb_threads_ = nb_threads;
condition_variables_ = new condition_variable[nb_threads];
thread_parameters_ = new ThreadParameters[nb_threads];
threads_ = new thread*[nb_threads];
exit_ = false;
for (int i = 0; i < nb_threads; ++i) {
thread_parameters_[i].message = to_string(i + 1);
thread_parameters_[i].exit = &exit_;
// Wait 'your' condition
thread_parameters_[i].input = &condition_variables_[i];
// Then set next one (of first one if you are the last).
thread_parameters_[i].output =
&condition_variables_[(i + 1) % nb_threads];
threads_[i] = new thread(Thread, &thread_parameters_[i]);
}
// Start the dance, free the first thread.
condition_variables_[0].notify_all();
}
~CircularPrint() {
// Ask threads to exit.
exit_ = true;
// Wait for all threads to end.
for (int i = 0; i < nb_threads_; ++i) {
threads_[i]->join();
delete threads_[i];
}
delete[] condition_variables_;
delete[] thread_parameters_;
delete[] threads_;
}
static void Thread(ThreadParameters* params) {
for (;;) {
if (*params->exit) {
return;
}
{
// Wait the mutex. We don't really care, by condition variables
// need a mutex.
// Though the mutex will be useful for the real assignement.
unique_lock<mutex> lock(mutex_);
// Wait for the input condition variable (frees the mutex before waiting).
params->input->wait(lock);
}
cout << params->message << endl;
// Free next thread.
params->output->notify_all();
}
}
private:
int nb_threads_;
condition_variable* condition_variables_;
ThreadParameters* thread_parameters_;
thread** threads_;
bool exit_;
static mutex mutex_;
};
mutex CircularPrint::mutex_;
int main() {
CircularPrint printer(10);
sleep(3);
return 0;
}
using vector<shared_ptr<...>> would be more elegant than just arrays, though this works:
g++ -std=c++11 -o test test.cc -pthread -Wl,--no-as-needed
./test

pointer being freed was not allocated error?

I have seen many posts for this error. But I'm not reserving memory dynamically or doing anything in destructor:
This program is SSJF algorithm for selecting cylinder in operating system.
I have a simple class called IO:
class IO
{
public:
IO();
IO(int,int);
void setIO(int,int);
~IO();
int trackNo;
int arrival;
int start;
int end;
bool finished;
};
Here is the implementation of the class::
IO::IO(int arr, int tNum)
{
this->arrival = arr;
this->trackNo = tNum;
this->start = 0;
this->end = 0;
}
IO::IO()
{
}
IO::~IO()
{
}
void IO::setIO(int t1, int t2)
{
this->trackNo = t1;
this->arrival = t2;
}
And finally here is part of main program:
list<IO> myList;
....
myList.push_back(tmpIO); //Add to the list
...
list<IO> wt_list;
And later I'm trying to do some operations. I have deleted some of the part which is not related.
//list<IO>::iterator itMin;
while(myList.size()>0)
{
//If it is the first input just get it
if(f)
{
IO selected = myList.front();
curr_time += selected.arrival + selected.trackNo;
f=false;
cout << selected.arrival<<endl;
lastPos = selected.trackNo;
myList.pop_front();
}
//Check if there is any item to add to queue
while(myList.front().arrival < curr_time)
{
wt_list.push_back(myList.front());
myList.pop_front(); //Error is coming from this line
}
while(wt_list.size()>0)
{
}
Error message:
malloc: * error for object 0x10f68b3e0: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
Anyone can help me and explain why I get this error and how can I skip it?
The simplest code I can come up with to reproduce this error looks like this:
#include <list>
int main()
{
std::list<int> mylist;
mylist.pop_front();
}
I can prevent the error by doing:
#include <list>
int main()
{
std::list<int> mylist;
if (!mylist.empty())
{
mylist.pop_front();
}
}
You're calling:
myList.pop_front();
...within a while-loop, which in turn is within a while-loop that also calls myList.pop_front().
I can only suggest that you debug your code to see how many times pop_front() is invoked for mylist. My money is on it being more than mylist.size() times, hence my question in the comments (with new emphasis):
How many items are in myList when the error is thrown?
Perhaps the simplest fix will be to replace...
//Check if there is any item to add to queue
while(myList.front().arrival < curr_time)
{
wt_list.push_back(myList.front());
myList.pop_front(); //Error is coming from this line
}
while(wt_list.size()>0)
{
}
...with...
while (!mylist.empty() && myList.front().arrival < curr_time)
{
wt_list.push_back(myList.front());
myList.pop_front();
}
while (!wt_list.empty())
{
}
...but it's hard to tell from the snippet you've provided.