s4eed
s4eed

Reputation: 7891

How to force a part of program to run just once?

I'm writing a c++ program that needs database and I'm using SQLite. I have a function, createTables(), that creates tables inside my database. But the part of program that really bothers me is that I have to call createTables() every time my program starts. Although SQL queries for creating tables are something like this :

CREATE TABLE IF NOT EXISTS table_name

But I want to know if it's possible to run a part of code just once without using if or other conditional statements. Can I change the program workflow by itself? Can a program change itself?
For example suppose that the original code is :

createTables();
otherPartOfProgram();

But for next time ( suppose tables were created successfully in previous run ) Program changed itself and workflow is something like :

otherPartOfProgram();

Upvotes: 0

Views: 129

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

The standard library has a solution, although it wasn't designed your for your situation:

#include <mutex>

std::once_flag flag;
void f();             // to be called once

void main_function()
{
    std::call_once(flag, f);
    // ...
}

Upvotes: 2

That cannot be done directly. You could store outside of your program (configuration file, registry...) the fact that the tables were created, or change the createTables function so that you test whether they exist before trying to create them.

A simpler approach, though, is have the tables as a precondition to running your program. Have some external code create them.

Upvotes: 3

Related Questions