Skip to content

Latest commit

 

History

History
122 lines (99 loc) · 2.86 KB

lock-file.md

File metadata and controls

122 lines (99 loc) · 2.86 KB
description title ms.date api_name api_location api_type topic_type f1_keywords helpviewer_keywords ms.assetid
Learn more about: _lock_file
_lock_file
4/2/2020
_lock_file
_o__lock_file
msvcrt.dll
msvcr80.dll
msvcr90.dll
msvcr100.dll
msvcr100_clr0400.dll
msvcr110.dll
msvcr110_clr0400.dll
msvcr120.dll
msvcr120_clr0400.dll
ucrtbase.dll
api-ms-win-crt-filesystem-l1-1-0.dll
DLLExport
apiref
_lock_file
lock_file
file locking [C++]
_lock_file function
lock_file function
75c7e0e6-efff-4747-b6ed-9bcf2b0894c3

_lock_file

Locks a FILE object to ensure consistency for threads accessing the FILE object concurrently.

Syntax

void _lock_file( FILE* file );

Parameters

file
File handle.

Remarks

The _lock_file function locks the FILE object specified by file. The underlying file isn't locked by _lock_file. Use _unlock_file to release the lock on the file. Calls to _lock_file and _unlock_file must be matched in a thread.

By default, this function's global state is scoped to the application. To change this behavior, see Global state in the CRT.

Requirements

Routine Required header
_lock_file <stdio.h>

For more compatibility information, see Compatibility.

Example

// crt_lock_file.c
// This example creates multiple threads that write to standard output
// concurrently, first with _file_lock, then without.

#include <stdio.h>
#include <process.h>// _beginthread
#include <windows.h>// HANDLE

void Task_locked( void* str )
{
    for( int i=0; i<1000; ++i )
    {
        _lock_file( stdout );
        for( char* cp = (char*)str; *cp; ++cp )
        {
            _fputc_nolock( *cp, stdout );
        }
        _unlock_file( stdout );
    }
}

void Task_unlocked( void* str )
{
    for( int i=0; i<1000; ++i )
    {
        for( char* cp = (char*)str; *cp; ++cp )
        {
            fputc( *cp, stdout );
        }
    }
}

int main()
{
    HANDLE h[3];
    h[0] = (HANDLE)_beginthread( &Task_locked, 0, "First\n" );
    h[1] = (HANDLE)_beginthread( &Task_locked, 0, "Second\n" );
    h[2] = (HANDLE)_beginthread( &Task_locked, 0, "Third\n" );

    WaitForMultipleObjects( 3, h, true, INFINITE );

    h[0] = (HANDLE)_beginthread( &Task_unlocked, 0, "First\n" );
    h[1] = (HANDLE)_beginthread( &Task_unlocked, 0, "Second\n" );
    h[2] = (HANDLE)_beginthread( &Task_unlocked, 0, "Third\n" );

    WaitForMultipleObjects( 3, h, true, INFINITE );
}
...
First
Second
First
Second
Third
Second
Third
Second
...
FSiercsotn
dF
iSrescto
nFdi
rSsetc
oFnidr
sSte
cFoinrds
tS
eFciornsdt

See also

File handling
_creat, _wcreat
_open, _wopen
_unlock_file