线程之间共享数据 [英] Share data between threads

查看:127
本文介绍了线程之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现,应该并行使用线程或任务运行的算法。困难的是,我想要的线程/任务,与所有其他线程时他们最好的结果分享给时间。

I'm trying to implement an algorithm that should run in parallel using threads or tasks. The difficulty is that I want the threads/tasks to share their best results from time to time with all other threads.

的基本思想是:

//Accessible from each thread
IProducerConsumerCollection<MyObject> _bestObjects;

//Executed in each thread
DoSomeWork(int n){
    MyObject localObject;
    for(var i = 0; i < n; i++){
        //Do some calculations and store results in localObject
        if((i/n)%0.5 == 0)
        {
            //store localObject in _bestObjects
            //wait until each thread has stored its result in _bestObjects
            //get the best result from _bestObjects and go on
        } 
    }
}

如何使用的System.Threading或System.Threading.Tasks实现这一目标,是真的,任务不应该被用在长时间运行的操作?

How can this be achieved using System.Threading or System.Threading.Tasks and is it true that tasks should not be used for long running operations?

这不是我的问题有一个线程安全的集合,但使线程停止,公布结果,等到所有其他线程都publihed的结果,然后再重新打开。所有的线程将同时运行。 切割长话短说:

It's not my problem to have a thread safe collection but to make the threads stop, publish result, wait until all other threads have publihed their results to and then go on again. All threads will run simultaneously. Cutting a long story short:

  1. 请告诉我好长时间运行的操作?任务或线程或别的什么吗?
  2. 如何线程/ TAKS之间通信,以通知他们每个人的关于所有其他假设线程的数目在运行时设置(取决于可用核)的状态。

最好的问候

周杰伦

推荐答案

看dollowing例子。

Look at the dollowing example.

public class Worker
{
    public SharedData state;
    public void Work(SharedData someData)
    {
        this.state = someData;
        while (true) ;
    }

}

public class SharedData {
    X myX;
    public getX() { ... }
    public setX(anX) { ... }    
}

public class Sharing
{
    public static void Main()
    {
        SharedData data = new SharedDate()
        Worker work1 = new Worker(data);
        Worker work2 = new Worker(data);
        Thread thread = new Thread(new ThreadStart(work1.Work));
        thread.start();
        Thread thread2 = new Thread(new ThreadStart(work2.Work));
        thread2.start();
    }
}

这篇关于线程之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆