taskflowrs 0.1.1

A Rust implementation of TaskFlow — task-parallel programming with heterogeneous GPU support
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
# Parallel Execution Variants

TaskFlow-RS provides powerful variants for running taskflows multiple times, both sequentially and in parallel, with full async support.

## Features

- **Parallel run_n** - Run N instances concurrently
- **Sequential run_n** - Run N instances one after another
- **run_until** - Execute until condition is met
- **Async variants** - Full async/await support for all execution modes

## Synchronous API

### run_n - Parallel Execution

Run N instances of a taskflow concurrently:

```rust
use taskflow_rs::{Executor, Taskflow};
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};

let mut executor = Executor::new(4);
let counter = Arc::new(AtomicUsize::new(0));

// Run 10 instances in parallel
executor.run_n(10, || {
    let c = counter.clone();
    let mut taskflow = Taskflow::new();
    
    taskflow.emplace(move || {
        c.fetch_add(1, Ordering::Relaxed);
    });
    
    taskflow
}).wait();

assert_eq!(counter.load(Ordering::Relaxed), 10);
```

**Performance:**
- All instances run concurrently
- Each instance gets its own executor thread pool
- Near-linear scaling up to CPU core count

### run_n_sequential - Sequential Execution

Run N instances one after another:

```rust
let mut executor = Executor::new(4);

// Run 5 instances sequentially
executor.run_n_sequential(5, || {
    let mut taskflow = Taskflow::new();
    taskflow.emplace(|| println!("Task"));
    taskflow
}).wait();
```

**Use when:**
- Instances depend on each other
- Shared resources need serial access
- Want predictable execution order

### run_until - Conditional Execution

Execute repeatedly until a condition is met:

```rust
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};

let mut executor = Executor::new(4);
let sum = Arc::new(AtomicUsize::new(0));

executor.run_until(
    || {
        let s = sum.clone();
        let mut taskflow = Taskflow::new();
        
        taskflow.emplace(move || {
            let value = rand::random::<usize>() % 10 + 1;
            s.fetch_add(value, Ordering::Relaxed);
        });
        
        taskflow
    },
    || sum.load(Ordering::Relaxed) >= 100
).wait();

println!("Final sum: {}", sum.load(Ordering::Relaxed));
```

**Use cases:**
- Iterative algorithms
- Accumulation until threshold
- Retry logic with conditions

## Asynchronous API

### run_n_async - Parallel Async Execution

Run N async instances concurrently:

```rust
use taskflow_rs::{AsyncExecutor, Taskflow};
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};

#[tokio::main]
async fn main() {
    let executor = AsyncExecutor::new(4);
    let counter = Arc::new(AtomicUsize::new(0));
    
    executor.run_n_async(5, || {
        let c = counter.clone();
        let mut taskflow = Taskflow::new();
        
        taskflow.emplace_async(move || {
            let c = c.clone();
            async move {
                // Async I/O operation
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                c.fetch_add(1, Ordering::Relaxed);
            }
        });
        
        taskflow
    }).await;
    
    assert_eq!(counter.load(Ordering::Relaxed), 5);
}
```

### run_n_sequential_async - Sequential Async Execution

Run N async instances sequentially:

```rust
let executor = AsyncExecutor::new(4);

executor.run_n_sequential_async(3, || {
    let mut taskflow = Taskflow::new();
    taskflow.emplace_async(|| async {
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
    });
    taskflow
}).await;
```

### run_until_async - Conditional Async Execution

Execute async taskflows until condition is met:

```rust
let executor = AsyncExecutor::new(4);
let sum = Arc::new(AtomicUsize::new(0));

let s = sum.clone();
executor.run_until_async(
    move || {
        let s = s.clone();
        let mut taskflow = Taskflow::new();
        
        taskflow.emplace_async(move || {
            let s = s.clone();
            async move {
                tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
                s.fetch_add(5, Ordering::Relaxed);
            }
        });
        
        taskflow
    },
    || sum.load(Ordering::Relaxed) >= 50
).await;
```

## Complete API Reference

### Executor (Sync)

```rust
impl Executor {
    /// Run N instances concurrently
    pub fn run_n<F>(&mut self, n: usize, factory: F) -> TaskflowFuture
    where F: Fn() -> Taskflow + Send + Sync + 'static;
    
    /// Run N instances sequentially
    pub fn run_n_sequential<F>(&mut self, n: usize, factory: F) -> TaskflowFuture
    where F: FnMut() -> Taskflow;
    
    /// Run until condition is met
    pub fn run_until<F, P>(&mut self, factory: F, predicate: P) -> TaskflowFuture
    where
        F: FnMut() -> Taskflow,
        P: FnMut() -> bool;
}
```

### AsyncExecutor (Async)

```rust
impl AsyncExecutor {
    /// Run N instances concurrently (async)
    pub async fn run_n_async<F>(&self, n: usize, factory: F)
    where F: Fn() -> Taskflow + Send + Sync;
    
    /// Run N instances sequentially (async)
    pub async fn run_n_sequential_async<F>(&self, n: usize, factory: F)
    where F: Fn() -> Taskflow;
    
    /// Run until condition is met (async)
    pub async fn run_until_async<F, P>(&self, factory: F, predicate: P)
    where
        F: Fn() -> Taskflow,
        P: FnMut() -> bool;
}
```

## Performance Comparison

### Sequential vs Parallel (5 instances, 100ms each)

| Mode | Time | Speedup |
|------|------|---------|
| Sequential | 500ms | 1.0x |
| Parallel (4 cores) | 125ms | 4.0x |
| Parallel (8 cores) | 100ms | 5.0x |

### Async Parallel (5 instances, 100ms I/O each)

| Mode | Time | Speedup |
|------|------|---------|
| Sequential Async | 500ms | 1.0x |
| Parallel Async | 100ms | 5.0x |

## Use Cases

### 1. Batch Processing

Process multiple data batches in parallel:

```rust
let mut executor = Executor::new(4);

executor.run_n(num_batches, || {
    let mut taskflow = Taskflow::new();
    
    let load = taskflow.emplace(|| load_batch());
    let process = taskflow.emplace(|| process_batch());
    let save = taskflow.emplace(|| save_batch());
    
    load.precede(&process);
    process.precede(&save);
    
    taskflow
}).wait();
```

### 2. Monte Carlo Simulation

Run multiple simulations in parallel:

```rust
let results = Arc::new(Mutex::new(Vec::new()));

executor.run_n(num_simulations, || {
    let r = results.clone();
    let mut taskflow = Taskflow::new();
    
    taskflow.emplace(move || {
        let result = run_simulation();
        r.lock().unwrap().push(result);
    });
    
    taskflow
}).wait();

let average = calculate_average(&results.lock().unwrap());
```

### 3. Parallel API Requests

Make multiple API requests concurrently:

```rust
let executor = AsyncExecutor::new(8);

executor.run_n_async(num_requests, || {
    let mut taskflow = Taskflow::new();
    
    taskflow.emplace_async(|| async {
        let response = reqwest::get(url).await?;
        process_response(response).await
    });
    
    taskflow
}).await;
```

### 4. Retry Logic

Retry until success:

```rust
let success = Arc::new(AtomicBool::new(false));

executor.run_until(
    || {
        let s = success.clone();
        let mut taskflow = Taskflow::new();
        
        taskflow.emplace(move || {
            if try_operation() {
                s.store(true, Ordering::Relaxed);
            }
        });
        
        taskflow
    },
    || success.load(Ordering::Relaxed)
).wait();
```

### 5. Training Epochs

Run training epochs until convergence:

```rust
let loss = Arc::new(Mutex::new(f64::MAX));

executor.run_until(
    || {
        let l = loss.clone();
        let mut taskflow = Taskflow::new();
        
        taskflow.emplace(move || {
            let new_loss = train_epoch();
            *l.lock().unwrap() = new_loss;
        });
        
        taskflow
    },
    || *loss.lock().unwrap() < threshold
).wait();
```

## Best Practices

### 1. Choose the Right Mode

```rust
// ✓ Good - Independent instances
executor.run_n(100, || create_taskflow());

// ✗ Bad - Sequential when order doesn't matter
executor.run_n_sequential(100, || create_taskflow());
```

### 2. Handle Shared State Properly

```rust
// ✓ Good - Thread-safe shared state
let counter = Arc::new(AtomicUsize::new(0));
executor.run_n(10, move || {
    let c = counter.clone();
    // ...
});

// ✗ Bad - Mutable shared state without synchronization
let mut counter = 0;  // Won't compile!
```

### 3. Set Reasonable Limits

```rust
// ✓ Good - Limited parallelism
let max_parallel = num_cpus::get();
executor.run_n(max_parallel, || taskflow);

// ✗ Bad - Excessive parallelism
executor.run_n(10000, || taskflow);  // Too many threads!
```

### 4. Avoid Blocking in Async

```rust
// ✓ Good - Use async I/O
taskflow.emplace_async(|| async {
    tokio::time::sleep(duration).await;
});

// ✗ Bad - Blocking in async context
taskflow.emplace_async(|| async {
    std::thread::sleep(duration);  // Blocks executor!
});
```

## Examples

### Sync Example

```bash
cargo run --example parallel_run_n
```

Expected output:
```
=== Parallel run_n Demo ===

1. Sequential vs Parallel Execution
   Sequential (run_n_sequential):
     Time: 502ms

   Parallel (run_n):
     Time: 128ms

   Speedup: 3.92x
   ✓ Parallel execution is faster

2. Parallel Instances
   Running 10 instances in parallel:
     [Instance 0] Executing
     [Instance 1] Executing
     ...
   Total executions: 10
   ✓ All instances executed correctly
```

### Async Example

```bash
cargo run --features async --example async_run_variants
```

Expected output:
```
=== Async Execution Variants Demo ===

1. Async Parallel run_n
   Running 5 async instances in parallel:
     [Instance 0] Starting
     [Instance 1] Starting
     ...
   Total executions: 5
   ✓ All async instances completed
```

## See Also

- `Executor::run()` - Single execution
- `AsyncExecutor::run_async()` - Async single execution
- [RUN_VARIANTS.md](RUN_VARIANTS.md) - Original run variants docs