使用Async.Parallel时,为什么我只有一个线程ID?

时间:2016-05-29 11:10:19

标签: multithreading asynchronous f#

为什么在使用Async.Parallel时只有一个处理器ID?

代码:

class matrix{
public:
    matrix() {
        _arrayofarrays = new int*[10];
        for(int i = 0; i < 10; ++i)
            _arrayofarrays[i] = new int[10];
    }

    class Proxy {
    public:
        Proxy(int* _array) : _array(_array) { }

        int operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };

    Proxy operator[](int index) {
        return Proxy(_arrayofarrays[index]);
    }

private:
    int** _arrayofarrays;
};

输出:

open System
open System.Threading

[for i in 1..10 -> async {return i}] |> Async.Parallel
                                     |> Async.RunSynchronously
                                     |> Seq.iter (fun i -> printfn "Processor Id: %d Value: %d" Thread.CurrentThread.ManagedThreadId i)
Processor Id: 1 Value: 1
Processor Id: 1 Value: 2
Processor Id: 1 Value: 3
Processor Id: 1 Value: 4
Processor Id: 1 Value: 5
Processor Id: 1 Value: 6
Processor Id: 1 Value: 7
Processor Id: 1 Value: 8
Processor Id: 1 Value: 9
Processor Id: 1 Value: 10

1 个答案:

答案 0 :(得分:8)

您正在异步工作流程之外的主线程中执行printfn。试试这个:

[for i in 1..10 -> 
    async {return sprintf "Processor Id: %d Value: %d" Thread.CurrentThread.ManagedThreadId i}] 
|> Async.Parallel
|> Async.RunSynchronously