###  | # Boost.Threads ## call_once

Introduction
Header
Synopsis
Members
Example

## Introduction

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

## Header

    #include <boost/thread/once.hpp>

## Synopsis

    namespace boost {

    typedef [implementation defined] once_flag;
    const once_flag once_init = [implementation defined];
    void call_once(void (*func)(), once_flag& flag);

    } // namespace boost

## Reference

### 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 `once_init`.

### once_init

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

### call_once

       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 == once_init)
func();`

Postcondition: `flag` != `once_init`

## Example Usage

    #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 all rights reserved.