Win32 API 日本語リファレンス
ホームSystem.Threading › ReleaseSemaphore

ReleaseSemaphore

関数
セマフォのカウントを指定数だけ増加させて解放する。
DLLKERNEL32.dll呼出規約winapiSetLastErrorあり対応OSWindows XP 以降

シグネチャ

// KERNEL32.dll
#include <windows.h>

BOOL ReleaseSemaphore(
    HANDLE hSemaphore,
    INT lReleaseCount,
    INT* lpPreviousCount   // optional
);

パラメーター

名前方向説明
hSemaphoreHANDLEin

セマフォオブジェクトへのハンドル。 CreateSemaphore 関数または OpenSemaphore 関数がこのハンドルを返します。

このハンドルには SEMAPHORE_MODIFY_STATE アクセス権が必要です。詳細については、 Synchronization Object Security and Access Rights を参照してください。

lReleaseCountINTinセマフォオブジェクトの現在のカウントを増加させる量。値は 0 より大きくなければなりません。指定した量によってセマフォのカウントが、セマフォ作成時に指定された最大カウントを超えてしまう場合、カウントは変更されず、関数は FALSE を返します。
lpPreviousCountINT*outoptionalセマフォの以前のカウントを受け取る変数へのポインター。以前のカウントが不要な場合、このパラメーターは NULL にできます。

戻り値の型: BOOL

公式ドキュメント

指定したセマフォオブジェクトのカウントを、指定した値だけ増加させます。

戻り値

関数が成功した場合、戻り値は 0 以外の値です。

関数が失敗した場合、戻り値は 0 です。拡張エラー情報を取得するには、GetLastError を呼び出します。

解説(Remarks)

セマフォオブジェクトの状態は、カウントが 0 より大きいときはシグナル状態、カウントが 0 に等しいときは非シグナル状態になります。 CreateSemaphore 関数を呼び出すプロセスが、セマフォの初期カウントを指定します。セマフォのシグナル状態によって待機中のスレッドが解放されるたびに、セマフォのカウントは 1 ずつ減少します。

通常、アプリケーションはセマフォを使用して、リソースを使用するスレッド数を制限します。スレッドはリソースを使用する前に、 待機関数 のいずれかの呼び出しでセマフォハンドルを指定します。待機関数が戻ると、セマフォのカウントが 1 減少します。スレッドがリソースの使用を終えると、 ReleaseSemaphore を呼び出してセマフォのカウントを 1 増加させます。

ReleaseSemaphore のもう 1 つの用途は、アプリケーションの初期化中です。アプリケーションは初期カウント 0 でセマフォを作成できます。これによりセマフォの状態が非シグナル状態に設定され、すべてのスレッドが保護対象リソースへアクセスできないようにブロックされます。アプリケーションが初期化を完了すると、 ReleaseSemaphore を使用してカウントを最大値まで増加させ、保護対象リソースへの通常のアクセスを許可します。

lReleaseCount を負の数にできないため、 ReleaseSemaphore を使用してセマフォオブジェクトのカウントを減らすことはできません。アクセスを一時的に制限または減少させるには、セマフォのカウントが十分に減るまで、タイムアウト間隔を 0 にして WaitForSingleObject 関数を呼び出すループを作成します。(このループの実行中に、他のスレッドがカウントを減らす可能性があることに注意してください。) アクセスを復元するには、ループ内で WaitForSingleObject を呼び出した回数と等しいリリースカウントを指定して ReleaseSemaphore を呼び出します。

Examples

ReleaseSemaphore を使用する例については、 Using Semaphore Objects を参照してください。

出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// KERNEL32.dll
#include <windows.h>

BOOL ReleaseSemaphore(
    HANDLE hSemaphore,
    INT lReleaseCount,
    INT* lpPreviousCount   // optional
);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool ReleaseSemaphore(
    IntPtr hSemaphore,   // HANDLE
    int lReleaseCount,   // INT
    IntPtr lpPreviousCount   // INT* optional, out
);
<DllImport("KERNEL32.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function ReleaseSemaphore(
    hSemaphore As IntPtr,   ' HANDLE
    lReleaseCount As Integer,   ' INT
    lpPreviousCount As IntPtr   ' INT* optional, out
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
' hSemaphore : HANDLE
' lReleaseCount : INT
' lpPreviousCount : INT* optional, out
Declare PtrSafe Function ReleaseSemaphore Lib "kernel32" ( _
    ByVal hSemaphore As LongPtr, _
    ByVal lReleaseCount As Long, _
    ByVal lpPreviousCount As LongPtr) As Long
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

ReleaseSemaphore = ctypes.windll.kernel32.ReleaseSemaphore
ReleaseSemaphore.restype = wintypes.BOOL
ReleaseSemaphore.argtypes = [
    wintypes.HANDLE,  # hSemaphore : HANDLE
    ctypes.c_int,  # lReleaseCount : INT
    ctypes.POINTER(ctypes.c_int),  # lpPreviousCount : INT* optional, out
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('KERNEL32.dll')
ReleaseSemaphore = Fiddle::Function.new(
  lib['ReleaseSemaphore'],
  [
    Fiddle::TYPE_VOIDP,  # hSemaphore : HANDLE
    Fiddle::TYPE_INT,  # lReleaseCount : INT
    Fiddle::TYPE_VOIDP,  # lpPreviousCount : INT* optional, out
  ],
  Fiddle::TYPE_INT)
#[link(name = "kernel32")]
extern "system" {
    fn ReleaseSemaphore(
        hSemaphore: *mut core::ffi::c_void,  // HANDLE
        lReleaseCount: i32,  // INT
        lpPreviousCount: *mut i32  // INT* optional, out
    ) -> i32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", SetLastError = true)]
public static extern bool ReleaseSemaphore(IntPtr hSemaphore, int lReleaseCount, IntPtr lpPreviousCount);
"@
$api = Add-Type -MemberDefinition $sig -Name 'KERNEL32_ReleaseSemaphore' -Namespace Win32 -PassThru
# $api::ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
#uselib "KERNEL32.dll"
#func global ReleaseSemaphore "ReleaseSemaphore" sptr, sptr, sptr
; ReleaseSemaphore hSemaphore, lReleaseCount, varptr(lpPreviousCount)   ; 戻り値は stat
; hSemaphore : HANDLE -> "sptr"
; lReleaseCount : INT -> "sptr"
; lpPreviousCount : INT* optional, out -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
出力引数:
#uselib "KERNEL32.dll"
#cfunc global ReleaseSemaphore "ReleaseSemaphore" sptr, int, var
; res = ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
; hSemaphore : HANDLE -> "sptr"
; lReleaseCount : INT -> "int"
; lpPreviousCount : INT* optional, out -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
出力引数:
; BOOL ReleaseSemaphore(HANDLE hSemaphore, INT lReleaseCount, INT* lpPreviousCount)
#uselib "KERNEL32.dll"
#cfunc global ReleaseSemaphore "ReleaseSemaphore" intptr, int, var
; res = ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
; hSemaphore : HANDLE -> "intptr"
; lReleaseCount : INT -> "int"
; lpPreviousCount : INT* optional, out -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	kernel32 = windows.NewLazySystemDLL("KERNEL32.dll")
	procReleaseSemaphore = kernel32.NewProc("ReleaseSemaphore")
)

// hSemaphore (HANDLE), lReleaseCount (INT), lpPreviousCount (INT* optional, out)
r1, _, err := procReleaseSemaphore.Call(
	uintptr(hSemaphore),
	uintptr(lReleaseCount),
	uintptr(lpPreviousCount),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // BOOL
function ReleaseSemaphore(
  hSemaphore: THandle;   // HANDLE
  lReleaseCount: Integer;   // INT
  lpPreviousCount: Pointer   // INT* optional, out
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'ReleaseSemaphore';
result := DllCall("KERNEL32\ReleaseSemaphore"
    , "Ptr", hSemaphore   ; HANDLE
    , "Int", lReleaseCount   ; INT
    , "Ptr", lpPreviousCount   ; INT* optional, out
    , "Int")   ; return: BOOL
●ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount) = DLL("KERNEL32.dll", "bool ReleaseSemaphore(void*, int, void*)")
# 呼び出し: ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
# hSemaphore : HANDLE -> "void*"
# lReleaseCount : INT -> "int"
# lpPreviousCount : INT* optional, out -> "void*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

extern "kernel32" fn ReleaseSemaphore(
    hSemaphore: ?*anyopaque, // HANDLE
    lReleaseCount: i32, // INT
    lpPreviousCount: [*c]i32 // INT* optional, out
) callconv(std.os.windows.WINAPI) i32;
proc ReleaseSemaphore(
    hSemaphore: pointer,  # HANDLE
    lReleaseCount: int32,  # INT
    lpPreviousCount: ptr int32  # INT* optional, out
): int32 {.importc: "ReleaseSemaphore", stdcall, dynlib: "KERNEL32.dll".}
pragma(lib, "kernel32");
extern(Windows)
int ReleaseSemaphore(
    void* hSemaphore,   // HANDLE
    int lReleaseCount,   // INT
    int* lpPreviousCount   // INT* optional, out
);
ccall((:ReleaseSemaphore, "KERNEL32.dll"), stdcall, Int32,
      (Ptr{Cvoid}, Int32, Ptr{Int32}),
      hSemaphore, lReleaseCount, lpPreviousCount)
# hSemaphore : HANDLE -> Ptr{Cvoid}
# lReleaseCount : INT -> Int32
# lpPreviousCount : INT* optional, out -> Ptr{Int32}
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
int32_t ReleaseSemaphore(
    void* hSemaphore,
    int32_t lReleaseCount,
    int32_t* lpPreviousCount);
]]
local kernel32 = ffi.load("kernel32")
-- kernel32.ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
-- hSemaphore : HANDLE
-- lReleaseCount : INT
-- lpPreviousCount : INT* optional, out
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('KERNEL32.dll');
const ReleaseSemaphore = lib.func('__stdcall', 'ReleaseSemaphore', 'int32_t', ['void *', 'int32_t', 'int32_t *']);
// ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
// hSemaphore : HANDLE -> 'void *'
// lReleaseCount : INT -> 'int32_t'
// lpPreviousCount : INT* optional, out -> 'int32_t *'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("KERNEL32.dll", {
  ReleaseSemaphore: { parameters: ["pointer", "i32", "pointer"], result: "i32" },
});
// lib.symbols.ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
// hSemaphore : HANDLE -> "pointer"
// lReleaseCount : INT -> "i32"
// lpPreviousCount : INT* optional, out -> "pointer"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
int32_t ReleaseSemaphore(
    void* hSemaphore,
    int32_t lReleaseCount,
    int32_t* lpPreviousCount);
C, "KERNEL32.dll");
// $ffi->ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount);
// hSemaphore : HANDLE
// lReleaseCount : INT
// lpPreviousCount : INT* optional, out
// 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
// WINAPI(stdcall): x64 では呼出規約が統一されるため問題なし。x86 では __stdcall 対応のラッパが必要な場合あり。
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

public interface Kernel32 extends StdCallLibrary {
    Kernel32 INSTANCE = Native.load("kernel32", Kernel32.class);
    boolean ReleaseSemaphore(
        Pointer hSemaphore,   // HANDLE
        int lReleaseCount,   // INT
        IntByReference lpPreviousCount   // INT* optional, out
    );
}
@[Link("kernel32")]
lib LibKERNEL32
  fun ReleaseSemaphore = ReleaseSemaphore(
    hSemaphore : Void*,   # HANDLE
    lReleaseCount : Int32,   # INT
    lpPreviousCount : Int32*   # INT* optional, out
  ) : Int32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef ReleaseSemaphoreNative = Int32 Function(Pointer<Void>, Int32, Pointer<Int32>);
typedef ReleaseSemaphoreDart = int Function(Pointer<Void>, int, Pointer<Int32>);
final ReleaseSemaphore = DynamicLibrary.open('KERNEL32.dll')
    .lookupFunction<ReleaseSemaphoreNative, ReleaseSemaphoreDart>('ReleaseSemaphore');
// hSemaphore : HANDLE -> Pointer<Void>
// lReleaseCount : INT -> Int32
// lpPreviousCount : INT* optional, out -> Pointer<Int32>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function ReleaseSemaphore(
  hSemaphore: THandle;   // HANDLE
  lReleaseCount: Integer;   // INT
  lpPreviousCount: Pointer   // INT* optional, out
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'ReleaseSemaphore';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "ReleaseSemaphore"
  c_ReleaseSemaphore :: Ptr () -> Int32 -> Ptr Int32 -> IO CInt
-- hSemaphore : HANDLE -> Ptr ()
-- lReleaseCount : INT -> Int32
-- lpPreviousCount : INT* optional, out -> Ptr Int32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let releasesemaphore =
  foreign "ReleaseSemaphore"
    ((ptr void) @-> int32_t @-> (ptr int32_t) @-> returning int32_t)
(* hSemaphore : HANDLE -> (ptr void) *)
(* lReleaseCount : INT -> int32_t *)
(* lpPreviousCount : INT* optional, out -> (ptr int32_t) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library kernel32 (t "KERNEL32.dll"))
(cffi:use-foreign-library kernel32)

(cffi:defcfun ("ReleaseSemaphore" release-semaphore :convention :stdcall) :int32
  (h-semaphore :pointer)   ; HANDLE
  (l-release-count :int32)   ; INT
  (lp-previous-count :pointer))   ; INT* optional, out
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $ReleaseSemaphore = Win32::API::More->new('KERNEL32',
    'BOOL ReleaseSemaphore(HANDLE hSemaphore, int lReleaseCount, LPVOID lpPreviousCount)');
# my $ret = $ReleaseSemaphore->Call($hSemaphore, $lReleaseCount, $lpPreviousCount);
# hSemaphore : HANDLE -> HANDLE
# lReleaseCount : INT -> int
# lpPreviousCount : INT* optional, out -> LPVOID
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

公式の関連項目