diff options
| author | ame <[email protected]> | 2025-06-20 20:34:18 -0500 |
|---|---|---|
| committer | ame <[email protected]> | 2025-06-20 20:34:18 -0500 |
| commit | 76495ea9809c256ebc216e7aa2954c4e0592fd1d (patch) | |
| tree | 4f6b08a23632659199ebcb16b198ecf0ede1f5d7 /src/thread.c | |
| parent | e058a29d70dd299b7fc2a84cae5824fd03fbef84 (diff) | |
thread.mutex
Diffstat (limited to 'src/thread.c')
| -rw-r--r-- | src/thread.c | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/thread.c b/src/thread.c index a5eb892..6d4540d 100644 --- a/src/thread.c +++ b/src/thread.c @@ -85,6 +85,65 @@ int l_tunlock(lua_State* L){ return 0;
}
+int _mutex_lock(lua_State* L){
+ lua_pushstring(L, "_");
+ lua_gettable(L, 1);
+ pthread_mutex_t *lock = lua_touserdata(L, -1);
+
+ pthread_mutex_lock(lock);
+
+ return 0;
+}
+
+int _mutex_unlock(lua_State* L){
+ lua_pushstring(L, "_");
+ lua_gettable(L, 1);
+ pthread_mutex_t *lock = lua_touserdata(L, -1);
+
+ pthread_mutex_unlock(lock);
+
+ return 0;
+}
+
+int _mutex_free(lua_State* L){
+ lua_pushstring(L, "_");
+ lua_gettable(L, 1);
+ pthread_mutex_t *lock = lua_touserdata(L, -1);
+
+ if(lock != NULL){
+ pthread_mutex_destroy(&*lock);
+ free(lock);
+
+ luaI_tsetlud(L, 1, "_", NULL);
+ }
+
+ return 0;
+}
+
+int l_mutex(lua_State* L){
+ pthread_mutex_t *lock = malloc(sizeof * lock);
+
+ if(pthread_mutex_init(&*lock, NULL) != 0)
+ luaI_error(L, -1, "mutex init failed");
+
+ lua_newtable(L);
+ int idx = lua_gettop(L);
+ luaI_tsetlud(L, idx, "_", lock);
+ luaI_tsetcf(L, idx, "lock", _mutex_lock);
+ luaI_tsetcf(L, idx, "unlock", _mutex_unlock);
+ luaI_tsetcf(L, idx, "free", _mutex_free);
+
+ lua_newtable(L);
+ int midx = lua_gettop(L);
+ luaI_tsetcf(L, midx, "__gc", _mutex_free);
+
+ lua_pushvalue(L, midx);
+ lua_setmetatable(L, idx);
+ lua_pushvalue(L, idx);
+
+ return 1;
+}
+
int l_res(lua_State* L){
int return_count = lua_gettop(L) - 1;
lua_pushstring(L, "_");
|
