Share via


_lock_file

Sperrt ein FILE-Objekt, um die Konsistenz für Threads sicherzustellen, die gleichzeitig das FILE-Objekt aufrufen.

Syntax

void _lock_file( FILE* file );

Parameter

file
Dateihandle.

Hinweise

Die _lock_file-Funktion sperrt das FILE-Objekt, das von file angegeben ist. Die zugrunde liegende Datei ist nicht durch _lock_file. Wird verwendet _unlock_file , um die Sperre für die Datei freizugeben. Aufrufe von _lock_file und _unlock_file müssen in einem Thread übereinstimmen.

Standardmäßig gilt der globale Zustand dieser Funktion für die Anwendung. Informationen zum Ändern dieses Verhaltens finden Sie im Global state in the CRT.

Anforderungen

Routine Erforderlicher Header
_lock_file <stdio.h>

Weitere Informationen zur Kompatibilität finden Sie unter Kompatibilität.

Beispiel

// 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

Siehe auch

Dateiverarbeitung
_creat, _wcreat
_open, _wopen
_unlock_file