_lock_file

锁定 FILE 对象来确保同时访问 FILE 对象的线程的一致性。

void _lock_file(
   FILE* file
);

参数

  • file
    文件处理程序。

备注

_lock_file 函数锁定通过 file 指定的 FILE 对象。 相关文件不会由 _lock_file 锁定。 使用 _unlock_file 释放文件的锁定。 _lock_file 和 _unlock_file 的调用必须在线程中匹配。

要求

例程

必需的标头

_lock_file

<stdio.h>

有关更多兼容性信息,请参见“简介”中的兼容性

示例

// 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 );
}
  

.NET Framework 等效项

System::IO::FileStream::Lock

请参见

参考

文件处理

_creat、_wcreat

_open、_wopen

_unlock_file