15 Commits

Author SHA1 Message Date
HASUMI Hitoshi 0a21eef938 Fix mruby-task for PicoRuby Integration
With this PR, I can remove the original task.c in picoruby/picoruby and future development will be much easier.

## Add

### General

- C API functions exported with MRB_API for external integration:
  - mrb_execute_proc_synchronously() for synchronous proc execution
  - Task control APIs (mrb_create_task, mrb_suspend_task, mrb_resume_task, mrb_terminate_task, mrb_stop_task, mrb_task_value, mrb_task_status)
  - Task context management APIs for picoruby-sandbox (mrb_task_init_context, mrb_task_reset_context, mrb_task_proc_set)
  - Task.tick class method to get current tick count
- Comprehensive C API documentation with WASM integration examples

### For PicoRuby.wasm

- WASM/Emscripten support: Disable SIGALRM timer when __EMSCRIPTEN__ is defined, as JavaScript handles tick calls via setInterval
- Scheduler lock mechanism to prevent asynchronous task operations during synchronous execution (scheduler_lock counter in mrb_task_state)
- mrb_task_run_once() for single-step execution (event loop integration)

## Fix

### task.c
- Replace MRB_FIBER_TERMINATED with MRB_TASK_STOPPED just for clarity
- Allow suspending DORMANT and WAITING tasks in mrb_task_suspend (See comment in the source)
- Task context initialization by removing dummy callinfo push/pop

*NOTE*

With the dummy callinfo code that I deleted, IRB in PicoRuby ended SEGV.
If that code is mandatory, we need to discuss how to solve my problem.

### vm.c
- Handle MRB_TASK_CREATED status in VM's NORMAL_RETURN phase to properly stop tasks

----

These changes are necessary to make PicoRuby work.
Nevertheless, even with this patch, MicroRuby for Raspberry Pi Pico 2 is still unstable.
I would like to merge this PR anyway to make development easier by involving the PicoRuby community.
2026-01-11 17:07:04 +09:00
Yukihiro "Matz" Matsumoto dc7c6ed7a7 mruby-fiber,mruby-task: increase stack init size for 32-bit msvc
increase fiber_stack_init_size and task_stack_init_size from 16 to 64
to fix crashes on 32-bit msvc builds. git bisect identified commit
3246dd2 (which reduced sizes from 64 to 16) as causing the issue.
empirical testing shows 48 fails intermittently but 64 is stable on
32-bit msvc, likely due to different alignment or initialization
overhead on 32-bit platforms.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-18 23:34:10 +09:00
Yukihiro "Matz" Matsumoto 96e91004cd mruby-task: reduce initial stack sizes to match fiber allocations
reduced TASK_STACK_INIT_SIZE from 64 to 16 and TASK_CI_INIT_SIZE from 8 to 4,
matching mruby-fiber's conservative allocations. this saves 56 bytes per task
(320 bytes down to 160 bytes for initial allocations). stacks grow dynamically
via mrb_stack_extend when needed.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-16 14:56:13 +09:00
Yukihiro "Matz" Matsumoto 4b25faace0 mruby-task: further optimize struct with redundancy removal and unions
removes duplicate proc field and adds state-based union for result/timeslice,
achieving 16 bytes total savings per task (12.5% reduction):

optimizations:
- removed proc field (stored in c.ci->proc, already marked by gc): 8 bytes
- unified result/timeslice into state union (mutually exclusive): ~4 bytes
- combined with previous commit savings (priority_preemption, started, etc)

total reduction: 128 -> 112 bytes per task

impact:
- 10 tasks: 160 bytes saved
- 50 tasks: 800 bytes saved
- 100 tasks: 1.6 KB saved

all 1770 tests pass with zero functionality changes.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-16 14:56:13 +09:00
Yukihiro "Matz" Matsumoto 6d4fecc57c mruby-task: optimize mrb_task struct memory footprint
reduces per-task memory usage by 8 bytes (6.2%) through:
- removing priority_preemption field (always equals priority)
- removing started flag (inferred from context status)
- unifying wakeup_tick/join/mutex into single union

old size: 128 bytes
new size: 120 bytes

all tests pass with no functionality changes.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-16 14:56:12 +09:00
Yukihiro "Matz" Matsumoto 6ff5c7bfa9 mruby-task: rename mrb_tasks_run to mrb_task_run
follows mrb_{gem_name}_{operation} naming convention consistently
with other hal functions like mrb_task_hal_init. the plural form was
semantically correct but inconsistent with gem naming patterns.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-14 23:11:10 +09:00
Yukihiro "Matz" Matsumoto 872c3bcea4 mruby-task: remove unnecessary ifdef guards
remove MRB_USE_TASK_SCHEDULER ifdef guards from task.h and task.c
since the macro is always defined when compiling this gem

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-11 10:34:10 +09:00
Yukihiro "Matz" Matsumoto 8d61b67dc1 mruby-task: fix c++ compatibility warnings
- remove redundant MRB_TASK_CREATED/STOPPED macros from task.h since
  they are now properly defined in mrb_fiber_state enum in mruby.h
- declare kw_names array separately to avoid taking address of
  temporary array in c++ compilation

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-11 10:29:41 +09:00
Yukihiro "Matz" Matsumoto 1d90c19a36 mruby-task: rename constants for improved readability
Renamed constants to use more descriptive underscores:
- MRB_TASKSTATUS_* -> MRB_TASK_STATUS_*
- MRB_TASKREASON_* -> MRB_TASK_REASON_*

This improves code readability by making the constant names clearer.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-09 16:57:08 +09:00
Yukihiro "Matz" Matsumoto e7cbd8cc28 mruby-task: add gc protection and optimize task operations
Implements dual-mechanism GC protection and optimizes task lookup
using pointer arithmetic based on PicoRuby reference implementation.

GC Protection:
- Add mrb_gc_register/unregister to protect Task objects
- Implement mrb_task_mark_all() to mark task contexts during GC
- Store proc reference in mrb_task to prevent premature collection
- Integrate marking into gc.c root_scan_phase

Performance Optimizations:
- Add MRB2TASK macro for O(1) context-to-task conversion
- Optimize Task.current: O(n) queue search -> O(1) pointer arithmetic
- Optimize Task.pass: simplify to root context check
- Optimize Task.join: use MRB2TASK for current task lookup

Bug Fixes:
- Fix MRB_TASK_CREATED/STOPPED to use MRB_FIBER_TERMINATED
- Add safety check to prevent execution of terminated tasks
- Initialize callinfo PC to bytecode start in task_init_context

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:23 +09:00
Yukihiro "Matz" Matsumoto 4e7b6babe8 mruby-task: support multiple concurrent mrb_states
replace global_mrb with vm_list to support up to 8 concurrent mrb_state
instances. sigalrm handler now ticks all registered VMs. first VM
initializes timer, last VM stops timer. proper cleanup in hal_final.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:22 +09:00
Yukihiro "Matz" Matsumoto 47dfb771cf mruby-task: fix cooperative task yielding with Task.pass
this patch fixes several critical issues in the task scheduler:

1. vm integration for computed goto dispatch mode:
   - added task switching check in NEXT macro for computed goto
   - previous implementation only worked with switch dispatch mode
   - now Task.pass properly yields control to other tasks

2. task lifecycle tracking:
   - added 'started' flag to mrb_task structure
   - fixed first-run detection to avoid popping callinfo multiple times
   - vm overwrites context status during execution, making it unreliable

3. removed mrblib/task.rb:
   - empty Ruby method stubs were overriding C implementations
   - all task methods now properly implemented in C

4. cleaned up task scheduler loop:
   - proper task completion detection using switching flag
   - round-robin scheduling for tasks at same priority
   - clean scheduler exit when all tasks complete

tasks now cooperatively yield with Task.pass and complete cleanly.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:21 +09:00
Yukihiro "Matz" Matsumoto a0655615c9 mruby-task: rename mrb_tcb to mrb_task for clarity
replace confusing "tcb" (task control block) terminology with clearer
"mrb_task" naming:
- struct mrb_tcb -> struct mrb_task
- update mrb_task_state to use mrb_task pointers
- rename internal functions to avoid naming conflicts:
  - mrb_task_new -> task_alloc
  - mrb_task_free (lifecycle) -> task_free
- update field names for clarity:
  - tcb_join -> join
  - task (ruby object) -> self
  - value (return value) -> result

this makes the code more readable and follows mruby naming conventions
like mrb_context, mrb_irep, etc.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:20 +09:00
Yukihiro "Matz" Matsumoto dda60ca719 mruby-task: add core data structures to mrb_state
extend mrb_fiber_state enum with task-specific states:
- MRB_TASK_CREATED: task context initialized
- MRB_TASK_STOPPED: task execution finished

add mrb_task_state structure to mrb_state:
- task queues array (dormant, ready, waiting, suspended)
- tick counter for scheduling
- wakeup_tick for sleep timing
- switching flag for context switches

remove duplicate mrb_task_state definition from task.h since it is
now defined in include/mruby.h. all changes guarded by
MRB_USE_TASK_SCHEDULER for zero overhead when disabled.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:20 +09:00
Yukihiro "Matz" Matsumoto ae0d7a0c16 mruby-task: add initial gem structure with api skeleton
create mruby-task gem directory structure with:
- mrbgem.rake: gem specification with task scheduler define
- include/task.h: tcb structure and core scheduler declarations
- src/task.c: implementation skeleton with empty method stubs
- mrblib/task.rb: ruby api documentation and task::stat class

all methods have empty bodies ready for implementation.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:20 +09:00