共用方式為


_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