###  | # Boost.Threads ## Header <boost/thread/once.hpp>

## Contents

Introduction
Macros

BOOST_ONCE_INIT

Types

once_flag

Functions

call_once

Example(s)

## Introduction

Include the header <boost/thread/once.hpp> to define the `call_once` function, `once_flag` type and `BOOST_ONCE_INIT` constant.

The `call_once` function and `once_flag` type (statically initialized to `BOOST_ONCE_INIT`) can be used to run a routine exactly once. This can be used to initialize data in a thread-safe manner.

## Macros

    #define BOOST_ONCE_INIT implementation defined

This is a constant value used to initialize `once_flag` instances to indicate that the logically associated routine has not been run yet.

## Types

    typedef implementation defined once_flag;

This implementation defined type is used as a flag to insure a routine is called only once. Instances of this type should be statically initialized to `BOOST_ONCE_INIT`.

## Functions

    void call_once(void (*func)(), once_flag& flag);

Requires: The function `func` shall not throw exceptions.
Effects: As if (in an atomic fashion):

    if (flag == BOOST_ONCE_INIT)
        func();

Postconditions: `flag != BOOST_ONCE_INIT`

## Example(s)

    #include <boost/thread/thread.hpp>
    #include <boost/thread/once.hpp>
    #include <cassert>

    int value=0;
    boost::once_flag once = BOOST_ONCE_INIT;

    void init()
    {
        ++value;
    }

    void thread_proc()
    {
       boost::call_once(&init, once);
    }

    int main(int argc, char* argv[])
    {
       boost::thread_group threads;
       for (int i=0; i<5; ++i)
          threads.create_thread(&thread_proc);
       threads.join_all();
       assert(value == 1);
    }

Revised 05 November, 2001

© Copyright William E. Kempf 2001-2002. All Rights Reserved.

Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. William E. Kempf makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.