open-coroutine-core 0.7.0

The open-coroutine is a simple, efficient and generic coroutine library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use crate::co_pool::CoroutinePool;
use crate::common::beans::BeanFactory;
use crate::common::constants::{CoroutineState, PoolState, SyscallName, SyscallState, SLICE};
use crate::net::selector::{Event, Events, Poller, Selector};
use crate::scheduler::SchedulableCoroutine;
use crate::{error, impl_current_for, impl_display_by_debug, info};
use dashmap::DashSet;
use once_cell::sync::Lazy;
use rand::Rng;
use std::ffi::{c_char, c_int, c_void, CStr, CString};
use std::io::{Error, ErrorKind};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;

cfg_if::cfg_if! {
    if #[cfg(all(target_os = "linux", feature = "io_uring"))] {
        use dashmap::DashMap;
        use libc::{epoll_event, iovec, mode_t, msghdr, off_t, size_t, sockaddr, socklen_t};
        use std::ffi::{c_longlong, c_uint};
    }
}

cfg_if::cfg_if! {
    if #[cfg(all(windows, feature = "iocp"))] {
        use dashmap::DashMap;
        use std::ffi::{c_longlong, c_uint};
        use windows_sys::core::{PCSTR, PSTR};
        use windows_sys::Win32::Networking::WinSock::{
            LPWSAOVERLAPPED_COMPLETION_ROUTINE, SEND_RECV_FLAGS, SOCKADDR, SOCKET, WSABUF,
        };
        use windows_sys::Win32::System::IO::OVERLAPPED;
    }
}

#[repr(C)]
#[derive(Debug)]
pub(crate) struct EventLoop<'e> {
    stop: Arc<(Mutex<bool>, Condvar)>,
    shared_stop: Arc<(Mutex<AtomicUsize>, Condvar)>,
    cpu: usize,
    #[cfg(any(
        all(target_os = "linux", feature = "io_uring"),
        all(windows, feature = "iocp")
    ))]
    operator: crate::net::operator::Operator<'e>,
    #[allow(clippy::type_complexity)]
    #[cfg(any(
        all(target_os = "linux", feature = "io_uring"),
        all(windows, feature = "iocp")
    ))]
    syscall_wait_table: DashMap<usize, Arc<(Mutex<Option<c_longlong>>, Condvar)>>,
    selector: Poller,
    pool: CoroutinePool<'e>,
    phantom_data: PhantomData<&'e EventLoop<'e>>,
}

impl Drop for EventLoop<'_> {
    fn drop(&mut self) {
        if std::thread::panicking() {
            return;
        }
        self.stop_sync(Duration::from_secs(30))
            .unwrap_or_else(|e| panic!("Failed to stop event-loop {} due to {e} !", self.name()));
        assert_eq!(
            PoolState::Stopped,
            self.state(),
            "The event-loop is not stopped !"
        );
    }
}

impl<'e> Deref for EventLoop<'e> {
    type Target = CoroutinePool<'e>;

    fn deref(&self) -> &Self::Target {
        &self.pool
    }
}

impl DerefMut for EventLoop<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.pool
    }
}

impl Default for EventLoop<'_> {
    fn default() -> Self {
        let max_cpu_index = num_cpus::get();
        let random_cpu_index = rand::rng().random_range(0..max_cpu_index);
        Self::new(
            format!("open-coroutine-event-loop-{random_cpu_index}"),
            random_cpu_index,
            crate::common::constants::DEFAULT_STACK_SIZE,
            0,
            65536,
            0,
            Arc::new((Mutex::new(AtomicUsize::new(0)), Condvar::new())),
        )
        .expect("create event-loop failed")
    }
}

static COROUTINE_TOKENS: Lazy<DashSet<usize>> = Lazy::new(DashSet::new);

impl<'e> EventLoop<'e> {
    pub(super) fn new(
        name: String,
        cpu: usize,
        stack_size: usize,
        min_size: usize,
        max_size: usize,
        keep_alive_time: u64,
        shared_stop: Arc<(Mutex<AtomicUsize>, Condvar)>,
    ) -> std::io::Result<Self> {
        Ok(EventLoop {
            stop: Arc::new((Mutex::new(false), Condvar::new())),
            shared_stop,
            cpu,
            #[cfg(any(
                all(target_os = "linux", feature = "io_uring"),
                all(windows, feature = "iocp")
            ))]
            operator: crate::net::operator::Operator::new(cpu)?,
            #[cfg(any(
                all(target_os = "linux", feature = "io_uring"),
                all(windows, feature = "iocp")
            ))]
            syscall_wait_table: DashMap::new(),
            selector: Poller::new()?,
            pool: CoroutinePool::new(name, stack_size, min_size, max_size, keep_alive_time),
            phantom_data: PhantomData,
        })
    }

    /// Try to cancel a task from `CoroutinePool`.
    pub(super) fn try_cancel_task(name: &str) {
        CoroutinePool::try_cancel_task(name);
    }

    #[allow(trivial_numeric_casts, clippy::cast_possible_truncation)]
    fn token(syscall: SyscallName) -> usize {
        if let Some(co) = SchedulableCoroutine::current() {
            let boxed: &'static mut CString = Box::leak(Box::from(
                CString::new(co.name()).expect("build name failed!"),
            ));
            let cstr: &'static CStr = boxed.as_c_str();
            let token = cstr.as_ptr().cast::<c_void>() as usize;
            assert!(COROUTINE_TOKENS.insert(token));
            return token;
        }
        unsafe {
            cfg_if::cfg_if! {
                if #[cfg(windows)] {
                    let thread_id = windows_sys::Win32::System::Threading::GetCurrentThread();
                } else {
                    let thread_id = libc::pthread_self();
                }
            }
            let syscall_mask = <SyscallName as Into<&str>>::into(syscall).as_ptr() as usize;
            let token = thread_id as usize ^ syscall_mask;
            if SyscallName::nio() != syscall {
                eprintln!("generate token:{token} for {syscall}");
            }
            token
        }
    }

    pub(super) fn add_read_event(&self, fd: c_int) -> std::io::Result<()> {
        self.selector
            .add_read_event(fd, EventLoop::token(SyscallName::nio()))
    }

    pub(super) fn add_write_event(&self, fd: c_int) -> std::io::Result<()> {
        self.selector
            .add_write_event(fd, EventLoop::token(SyscallName::nio()))
    }

    pub(super) fn del_event(&self, fd: c_int) -> std::io::Result<()> {
        self.selector.del_event(fd)
    }

    pub(super) fn del_read_event(&self, fd: c_int) -> std::io::Result<()> {
        self.selector.del_read_event(fd)
    }

    pub(super) fn del_write_event(&self, fd: c_int) -> std::io::Result<()> {
        self.selector.del_write_event(fd)
    }

    pub(super) fn wait_event(&mut self, timeout: Option<Duration>) -> std::io::Result<()> {
        let left_time = if SchedulableCoroutine::current().is_some() {
            timeout
        } else if let Some(time) = timeout {
            Some(
                self.try_timed_schedule_task(time)
                    .map(Duration::from_nanos)?,
            )
        } else {
            self.try_schedule_task()?;
            None
        };
        self.wait_just(left_time)
    }

    /// Wait events happen.
    pub(super) fn timed_wait_just(&self, timeout: Option<Duration>) -> std::io::Result<()> {
        let timeout_time = timeout.map_or(u64::MAX, crate::common::get_timeout_time);
        loop {
            let left_time = timeout_time
                .saturating_sub(crate::common::now())
                .min(10_000_000);
            if left_time == 0 {
                //timeout
                return self.wait_just(Some(Duration::ZERO));
            }
            self.wait_just(Some(Duration::from_nanos(left_time)))?;
        }
    }

    pub(super) fn wait_just(&self, timeout: Option<Duration>) -> std::io::Result<()> {
        let mut left_time = timeout;
        if let Some(time) = left_time {
            let timestamp = crate::common::get_timeout_time(time);
            if let Some(co) = SchedulableCoroutine::current() {
                if let CoroutineState::Syscall((), syscall, SyscallState::Executing) = co.state() {
                    let new_state = SyscallState::Suspend(timestamp);
                    if co.syscall((), syscall, new_state).is_err() {
                        error!(
                            "{} change to syscall {} {} failed !",
                            co.name(),
                            syscall,
                            new_state
                        );
                    }
                }
            }
            if let Some(suspender) = crate::scheduler::SchedulableSuspender::current() {
                suspender.until(timestamp);
                //回来的时候等待的时间已经到了
                left_time = Some(Duration::ZERO);
            }
            if let Some(co) = SchedulableCoroutine::current() {
                if let CoroutineState::Syscall(
                    (),
                    syscall,
                    SyscallState::Callback | SyscallState::Timeout,
                ) = co.state()
                {
                    let new_state = SyscallState::Executing;
                    if co.syscall((), syscall, new_state).is_err() {
                        error!(
                            "{} change to syscall {} {} failed !",
                            co.name(),
                            syscall,
                            new_state
                        );
                    }
                }
            }
        }

        cfg_if::cfg_if! {
            if #[cfg(all(target_os = "linux", feature = "io_uring"))] {
                left_time = self.adapt_io_uring(left_time)?;
            } else if #[cfg(all(windows, feature = "iocp"))] {
                left_time = self.adapt_iocp(left_time)?;
            }
        }

        // use epoll/kevent/iocp
        let mut events = Events::with_capacity(1024);
        self.selector.select(&mut events, left_time)?;
        #[allow(clippy::explicit_iter_loop)]
        for event in events.iter() {
            let token = event.get_token();
            if event.readable() || event.writable() {
                unsafe { self.resume(token) };
            }
        }
        Ok(())
    }

    #[cfg(all(target_os = "linux", feature = "io_uring"))]
    fn adapt_io_uring(&self, mut left_time: Option<Duration>) -> std::io::Result<Option<Duration>> {
        if crate::net::operator::support_io_uring() {
            // use io_uring
            let (count, mut cq, left) = self.operator.select(left_time, 0)?;
            if count > 0 {
                for cqe in &mut cq {
                    let token = usize::try_from(cqe.user_data()).expect("token overflow");
                    if crate::common::constants::IO_URING_TIMEOUT_USERDATA == token {
                        continue;
                    }
                    // resolve completed read/write tasks
                    let result = c_longlong::from(cqe.result());
                    if let Some((_, pair)) = self.syscall_wait_table.remove(&token) {
                        let (lock, cvar) = &*pair;
                        let mut pending = lock.lock().expect("lock failed");
                        *pending = Some(result);
                        cvar.notify_one();
                    }
                    unsafe { self.resume(token) };
                }
            }
            if left != left_time {
                left_time = Some(left.unwrap_or(Duration::ZERO));
            }
        }
        Ok(left_time)
    }

    #[cfg(all(windows, feature = "iocp"))]
    fn adapt_iocp(&self, mut left_time: Option<Duration>) -> std::io::Result<Option<Duration>> {
        // use IOCP
        let (count, mut cq, left) = self.operator.select(left_time, 0)?;
        if count > 0 {
            for cqe in &mut cq {
                let token = cqe.token;
                if let Some((_, pair)) = self.syscall_wait_table.remove(&token) {
                    let (lock, cvar) = &*pair;
                    let mut pending = lock.lock().expect("lock failed");
                    *pending = Some(cqe.result);
                    cvar.notify_one();
                }
                unsafe { self.resume(token) };
            }
        }
        if left != left_time {
            left_time = Some(left.unwrap_or(Duration::ZERO));
        }
        Ok(left_time)
    }

    unsafe fn resume(&self, token: usize) {
        if COROUTINE_TOKENS.remove(&token).is_none() {
            return;
        }
        if let Ok(co_name) = CStr::from_ptr((token as *const c_void).cast::<c_char>()).to_str() {
            self.try_resume(co_name);
        }
    }

    pub(super) fn start(self) -> std::io::Result<Arc<Self>>
    where
        'e: 'static,
    {
        // init stop flag
        {
            let (lock, cvar) = &*self.stop;
            let mut pending = lock.lock().expect("lock failed");
            *pending = true;
            cvar.notify_one();
        }
        let thread_name = self.get_thread_name();
        let bean_name = self.name().to_string().leak();
        let bean_name_in_thread = self.name().to_string().leak();
        BeanFactory::init_bean(bean_name, self);
        BeanFactory::init_bean(
            &thread_name,
            std::thread::Builder::new()
                .name(thread_name.clone())
                .spawn(move || {
                    let consumer =
                        unsafe { BeanFactory::get_mut_bean::<Self>(bean_name_in_thread) }
                            .unwrap_or_else(|| panic!("bean {bean_name_in_thread} not exist !"));
                    {
                        let (lock, cvar) = &*consumer.shared_stop.clone();
                        let started = lock.lock().expect("lock failed");
                        _ = started.fetch_add(1, Ordering::Release);
                        cvar.notify_one();
                    }
                    // thread per core
                    info!(
                        "{} has started, bind to CPU:{}",
                        consumer.name(),
                        core_affinity::set_for_current(core_affinity::CoreId { id: consumer.cpu })
                    );
                    Self::init_current(consumer);
                    while PoolState::Running == consumer.state()
                        || !consumer.is_empty()
                        || consumer.get_running_size() > 0
                    {
                        _ = consumer.wait_event(Some(SLICE));
                    }
                    // notify stop flags
                    {
                        let (lock, cvar) = &*consumer.stop.clone();
                        let mut pending = lock.lock().expect("lock failed");
                        *pending = false;
                        cvar.notify_one();
                    }
                    {
                        let (lock, cvar) = &*consumer.shared_stop.clone();
                        let started = lock.lock().expect("lock failed");
                        _ = started.fetch_sub(1, Ordering::Release);
                        cvar.notify_one();
                    }
                    Self::clean_current();
                    info!("{} has exited", consumer.name());
                })?,
        );
        unsafe {
            Ok(Arc::from_raw(
                BeanFactory::get_bean::<Self>(bean_name)
                    .unwrap_or_else(|| panic!("bean {bean_name} not exist !")),
            ))
        }
    }

    fn get_thread_name(&self) -> String {
        format!("{}-thread", self.name())
    }

    pub(super) fn stop_sync(&mut self, wait_time: Duration) -> std::io::Result<()> {
        match self.state() {
            PoolState::Running => {
                assert_eq!(PoolState::Running, self.stopping()?);
                self.do_stop_sync(wait_time)
            }
            PoolState::Stopping => self.do_stop_sync(wait_time),
            PoolState::Stopped => Ok(()),
        }
    }

    fn do_stop_sync(&mut self, wait_time: Duration) -> std::io::Result<()> {
        let timeout_time = crate::common::get_timeout_time(wait_time);
        loop {
            let left_time = timeout_time.saturating_sub(crate::common::now());
            if 0 == left_time {
                return Err(Error::new(ErrorKind::TimedOut, "stop timeout !"));
            }
            self.wait_event(Some(Duration::from_nanos(left_time).min(SLICE)))?;
            if self.is_empty() && self.get_running_size() == 0 {
                assert_eq!(PoolState::Stopping, self.stopped()?);
                return Ok(());
            }
        }
    }

    pub(super) fn stop(&self, wait_time: Duration) -> std::io::Result<()> {
        match self.state() {
            PoolState::Running => {
                if BeanFactory::remove_bean::<JoinHandle<()>>(&self.get_thread_name()).is_some() {
                    assert_eq!(PoolState::Running, self.stopping()?);
                    return self.do_stop(wait_time);
                }
                Err(Error::new(
                    ErrorKind::Unsupported,
                    "use EventLoop::stop_sync instead !",
                ))
            }
            PoolState::Stopping => self.do_stop(wait_time),
            PoolState::Stopped => Ok(()),
        }
    }

    fn do_stop(&self, wait_time: Duration) -> std::io::Result<()> {
        //开启了单独的线程
        let (lock, cvar) = &*self.stop;
        let result = cvar
            .wait_timeout_while(
                lock.lock().expect("lock failed"),
                wait_time,
                |&mut pending| pending,
            )
            .expect("lock failed");
        if result.1.timed_out() {
            return Err(Error::new(ErrorKind::TimedOut, "stop timeout !"));
        }
        assert_eq!(PoolState::Stopping, self.stopped()?);
        assert!(BeanFactory::remove_bean::<Self>(self.name()).is_some());
        Ok(())
    }
}

impl_current_for!(EVENT_LOOP, EventLoop<'e>);

impl_display_by_debug!(EventLoop<'e>);

macro_rules! impl_io_uring {
    ( $syscall: ident($($arg: ident : $arg_type: ty),*) -> $result: ty ) => {
        #[cfg(all(target_os = "linux", feature = "io_uring"))]
        impl EventLoop<'_> {
            pub(super) fn $syscall(
                &self,
                $($arg: $arg_type),*
            ) -> std::io::Result<Arc<(Mutex<Option<c_longlong>>, Condvar)>> {
                let token = EventLoop::token(SyscallName::$syscall);
                self.operator.$syscall(token, $($arg, )*)?;
                let arc = Arc::new((Mutex::new(None), Condvar::new()));
                assert!(
                    self.syscall_wait_table.insert(token, arc.clone()).is_none(),
                    "The previous token was not retrieved in a timely manner"
                );
                Ok(arc)
            }
        }
    }
}

impl_io_uring!(epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *mut epoll_event) -> c_int);
impl_io_uring!(socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int);
impl_io_uring!(accept(fd: c_int, addr: *mut sockaddr, len: *mut socklen_t) -> c_int);
impl_io_uring!(accept4(fd: c_int, addr: *mut sockaddr, len: *mut socklen_t, flg: c_int) -> c_int);
impl_io_uring!(shutdown(fd: c_int, how: c_int) -> c_int);
impl_io_uring!(connect(fd: c_int, address: *const sockaddr, len: socklen_t) -> c_int);
impl_io_uring!(close(fd: c_int) -> c_int);
impl_io_uring!(recv(fd: c_int, buf: *mut c_void, len: size_t, flags: c_int) -> ssize_t);
impl_io_uring!(read(fd: c_int, buf: *mut c_void, count: size_t) -> ssize_t);
impl_io_uring!(pread(fd: c_int, buf: *mut c_void, count: size_t, offset: off_t) -> ssize_t);
impl_io_uring!(readv(fd: c_int, iov: *const iovec, iovcnt: c_int) -> ssize_t);
impl_io_uring!(preadv(fd: c_int, iov: *const iovec, iovcnt: c_int, offset: off_t) -> ssize_t);
impl_io_uring!(recvmsg(fd: c_int, msg: *mut msghdr, flags: c_int) -> ssize_t);
impl_io_uring!(send(fd: c_int, buf: *const c_void, len: size_t, flags: c_int) -> ssize_t);
impl_io_uring!(sendto(fd: c_int, buf: *const c_void, len: size_t, flags: c_int, addr: *const sockaddr, addrlen: socklen_t) -> ssize_t);
impl_io_uring!(write(fd: c_int, buf: *const c_void, count: size_t) -> ssize_t);
impl_io_uring!(pwrite(fd: c_int, buf: *const c_void, count: size_t, offset: off_t) -> ssize_t);
impl_io_uring!(writev(fd: c_int, iov: *const iovec, iovcnt: c_int) -> ssize_t);
impl_io_uring!(pwritev(fd: c_int, iov: *const iovec, iovcnt: c_int, offset: off_t) -> ssize_t);
impl_io_uring!(sendmsg(fd: c_int, msg: *const msghdr, flags: c_int) -> ssize_t);
impl_io_uring!(fsync(fd: c_int) -> c_int);
impl_io_uring!(mkdirat(dirfd: c_int, pathname: *const c_char, mode: mode_t) -> c_int);
impl_io_uring!(renameat(olddirfd: c_int, oldpath: *const c_char, newdirfd: c_int, newpath: *const c_char) -> c_int);
impl_io_uring!(renameat2(olddirfd: c_int, oldpath: *const c_char, newdirfd: c_int, newpath: *const c_char, flags: c_uint) -> c_int);

macro_rules! impl_iocp {
    ( $syscall: ident($($arg: ident : $arg_type: ty),*) -> $result: ty ) => {
        #[cfg(all(windows, feature = "iocp"))]
        impl EventLoop<'_> {
            #[allow(non_snake_case, clippy::too_many_arguments)]
            pub(super) fn $syscall(
                &self,
                $($arg: $arg_type),*
            ) -> std::io::Result<Arc<(Mutex<Option<c_longlong>>, Condvar)>> {
                let token = EventLoop::token(SyscallName::$syscall);
                self.operator.$syscall(token, $($arg, )*)?;
                let arc = Arc::new((Mutex::new(None), Condvar::new()));
                assert!(
                    self.syscall_wait_table.insert(token, arc.clone()).is_none(),
                    "The previous token was not retrieved in a timely manner"
                );
                Ok(arc)
            }
        }
    }
}

impl_iocp!(accept(fd: SOCKET, addr: *mut SOCKADDR, len: *mut c_int) -> c_int);
impl_iocp!(recv(fd: SOCKET, buf: PSTR, len: c_int, flags: SEND_RECV_FLAGS) -> c_int);
impl_iocp!(WSARecv(fd: SOCKET, buf: *const WSABUF, dwbuffercount: c_uint, lpnumberofbytesrecvd: *mut c_uint, lpflags : *mut c_uint, lpoverlapped: *mut OVERLAPPED, lpcompletionroutine : LPWSAOVERLAPPED_COMPLETION_ROUTINE) -> c_int);
impl_iocp!(send(fd: SOCKET, buf: PCSTR, len: c_int, flags: SEND_RECV_FLAGS) -> c_int);
impl_iocp!(WSASend(fd: SOCKET, buf: *const WSABUF, dwbuffercount: c_uint, lpnumberofbytesrecvd: *mut c_uint, dwflags : c_uint, lpoverlapped: *mut OVERLAPPED, lpcompletionroutine : LPWSAOVERLAPPED_COMPLETION_ROUTINE) -> c_int);

#[cfg(all(test, not(all(unix, feature = "preemptive"))))]
mod tests {
    use crate::net::event_loop::EventLoop;
    use std::time::Duration;

    #[test]
    fn test_simple() -> std::io::Result<()> {
        let mut event_loop = EventLoop::default();
        event_loop.set_max_size(1);
        _ = event_loop.submit_task(None, |_| panic!("test panic, just ignore it"), None, None)?;
        _ = event_loop.submit_task(
            None,
            |_| {
                println!("2");
                Some(2)
            },
            None,
            None,
        )?;
        event_loop.stop_sync(Duration::from_secs(3))
    }

    #[ignore]
    #[test]
    fn test_simple_auto() -> std::io::Result<()> {
        let event_loop = EventLoop::default().start()?;
        event_loop.set_max_size(1);
        _ = event_loop.submit_task(None, |_| panic!("test panic, just ignore it"), None, None)?;
        _ = event_loop.submit_task(
            None,
            |_| {
                println!("2");
                Some(2)
            },
            None,
            None,
        )?;
        event_loop.stop(Duration::from_secs(3))
    }
}