Skip to content

Instantly share code, notes, and snippets.

@coderodde
Created January 11, 2019 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderodde/71bc30c58be76413a8d78b028c68c6a2 to your computer and use it in GitHub Desktop.
Save coderodde/71bc30c58be76413a8d78b028c68c6a2 to your computer and use it in GitHub Desktop.
Windows port for a semaphore data type.
#include "semaphore_impl.h"
#include <windows.h>
static const char* CLASS = "net/coderodde/util/concurrent/WindowsSemaphoreImpl";
static const char* FIELD = "semaphoreHandle";
static HANDLE get_semaphore_handle(JNIEnv* env, jobject obj)
{
jclass clazz = env->FindClass(CLASS);
jfieldID fid = env->GetFieldID(clazz, FIELD, "J");
return (HANDLE) env->GetLongField(obj, fid);
}
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_init(
JNIEnv* env,
jobject obj,
jint maxCount,
jint count)
{
// Create a handle to a semaphore.
HANDLE semaphore;
semaphore = CreateSemaphore(NULL,
count,
maxCount,
NULL);
// Get to the 'semaphoreHandle' field.
const jclass clazz = env->FindClass(CLASS);
const jfieldID semaphore_field_id = env->GetFieldID(clazz, FIELD, "J");
// Store the value of the semaphore to the Java semaphore object.
env->SetLongField(obj, semaphore_field_id, (jlong) semaphore);
}
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_clean(
JNIEnv* env,
jobject obj)
{
CloseHandle(get_semaphore_handle(env, obj));
}
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_lock(
JNIEnv* env,
jobject obj)
{
WaitForSingleObject(get_semaphore_handle(env, obj), INFINITE);
}
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_unlock(
JNIEnv* env,
jobject obj)
{
ReleaseSemaphore(get_semaphore_handle(env, obj), 1L, NULL);
}
#include <jni.h>
#ifndef WINDOWS_SEMAPHORE_IMPL_H
#define WINDOWS_SEMAPHORE_IMPL_H
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_init(
JNIEnv*,
jobject,
jint,
jint);
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_clean(JNIEnv*, jobject);
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_lock(JNIEnv*, jobject);
JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_unlock(JNIEnv*, jobject);
#ifdef __cplusplus
}
#endif
#endif // WINDOWS_SEMAPHORE_IMPL_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment