简体   繁体   中英

Ending a function in C++

I have a C++ function called write() that is supposed to write a large number of bytes on the users HDD. This woud normally take more than 30 seconds, so I want to give the user the ability to Abort operation from a GUI (created with Qt).

So I have the button generate_button . When this button is clicked() , I want to have something to end the function, wherever its progress is.

I thought about threads, but I am not sure. Can you advice me please?

I would probably use a thread. It should be quite simple to check a variable to see if the operation has been canceled.

Use a mutex to lock access to your cancel variable. That will make sure it is read and written in a proper way for multiple threads. Another option is if you are using C++11 use an atomic variable.

Break your large write into blocks of smaller size. 8 to 64 kilobytes should work. After writing each block check your cancel variable and if set, exit the thread.

Place the code that actually does the writing in a worker thread. Have a shared variable (one that is either atomic, or protected by a mutex). Have the worker thread check its value each iteration. If the user presses the "Abort" button, set the value for the variable.

You should use threads if this is a long running operation.

Since you are using C++11, std::atomic<bool> would probably serve you well.

Threaded guarantees that you will have a responsive GUI. But there is a learning curve to using a thread in this manner.

A threadless way to do this is to have in your routine that writes to the harddrive in the GUI thread, but gives time to the GUI thread to stay responsive.

QObject::connect(my_cancel_button, SIGNAL(clicked()), file_writer, SLOT(setCanceled()));

// open file for writing
QFile file("filename.txt");
file.open(//... );//

while(still_have_data_to_write && !canceled)
{
    write( <1 MB of data> ); // or some other denomination of data

    qApp->processEvents();// allows the gui to respond to events such as clicks on buttons

    // update a progress bar... using a counter as a ratio of the total file size
    emit updateProgressBar(count++);
}

if( canceled )
{
     file.close();
     // delete the partial file using QDir
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM