@@ -5,6 +5,7 @@ const { spawnSyncAndAssert } = require('../common/child_process');
55const assert = require ( 'node:assert' ) ;
66const { spawnSync } = require ( 'node:child_process' ) ;
77const { test } = require ( 'node:test' ) ;
8+ const { Worker } = require ( 'node:worker_threads' ) ;
89
910common . skipIfFFIMissing ( ) ;
1011
@@ -87,6 +88,7 @@ test('ffi exports expected API surface', () => {
8788 'exportArrayBufferView' ,
8889 'exportBuffer' ,
8990 'exportString' ,
91+ 'getCurrentEventLoop' ,
9092 'getFloat32' ,
9193 'getFloat64' ,
9294 'getInt16' ,
@@ -135,6 +137,7 @@ test('ffi exports expected API surface', () => {
135137 assert . strictEqual ( typeof ffi . getUint64 , 'function' ) ;
136138 assert . strictEqual ( typeof ffi . getFloat32 , 'function' ) ;
137139 assert . strictEqual ( typeof ffi . getFloat64 , 'function' ) ;
140+ assert . strictEqual ( typeof ffi . getCurrentEventLoop , 'function' ) ;
138141 assert . strictEqual ( typeof ffi . setInt8 , 'function' ) ;
139142 assert . strictEqual ( typeof ffi . setUint8 , 'function' ) ;
140143 assert . strictEqual ( typeof ffi . setInt16 , 'function' ) ;
@@ -180,3 +183,33 @@ test('ffi.types exports canonical type constants', () => {
180183 assert . deepStrictEqual ( ffi . types , expected ) ;
181184 assert . strictEqual ( Object . isFrozen ( ffi . types ) , true ) ;
182185} ) ;
186+
187+ test ( 'ffi.getCurrentEventLoop returns the current thread event loop address' , async ( ) => {
188+ const ffi = require ( 'node:ffi' ) ;
189+ const mainLoop = ffi . getCurrentEventLoop ( ) ;
190+
191+ assert . strictEqual ( typeof mainLoop , 'bigint' ) ;
192+ assert . ok ( mainLoop > 0n ) ;
193+ assert . strictEqual ( ffi . getCurrentEventLoop ( ) , mainLoop ) ;
194+
195+ const workerLoop = await new Promise ( ( resolve , reject ) => {
196+ const worker = new Worker ( `
197+ const { parentPort } = require('node:worker_threads');
198+ const ffi = require('node:ffi');
199+ const loop = ffi.getCurrentEventLoop();
200+
201+ parentPort.postMessage([loop, ffi.getCurrentEventLoop()]);
202+ ` , { eval : true } ) ;
203+
204+ worker . on ( 'message' , resolve ) ;
205+ worker . on ( 'error' , reject ) ;
206+ worker . on ( 'exit' , ( code ) => {
207+ if ( code !== 0 ) reject ( new Error ( `Worker stopped with exit code ${ code } ` ) ) ;
208+ } ) ;
209+ } ) ;
210+
211+ assert . strictEqual ( typeof workerLoop [ 0 ] , 'bigint' ) ;
212+ assert . ok ( workerLoop [ 0 ] > 0n ) ;
213+ assert . strictEqual ( workerLoop [ 0 ] , workerLoop [ 1 ] ) ;
214+ assert . notStrictEqual ( workerLoop [ 0 ] , mainLoop ) ;
215+ } ) ;
0 commit comments