在list中有100个任务,我想开10个线程去处理这个100个任务,要考虑各个线程中的资源共享问题,以及如果100个中的某个任务被另外的线程处理了,就要锁定,大家能否给个思路啊?
每个任务返回一个结果写到一个共用的Arraylist中去,全部处理完毕然后把结果返回。大家给个思路,最好有代码我看看,谢谢了!

解决方案 »

  1.   

    需要PV信号量。操作系统中的生产者消费者问题
    信号量表示某个资源的数量,p是+1操作,v是减1操作,一旦有一个线程访问这个资源就+1,一个线程释放这个资源就减1......
      

  2.   


    实现线程的调用方法类
    /// <summary>
    /// Summary description for AtpCodeThreadSearch.
    /// </summary>
    public class AtpCodeThreadSearch
    {
    // synchronization primitive than can also be used for interprocess synchronization.  
    private Mutex mut = new Mutex();
    // The all usefult Contract
    private ArrayList sortedFil = new ArrayList();
    // The Temp all usefult Contract
    private ArrayList tempSortedFil = new ArrayList();
    // Get the SearchAtpcode object
    private SearchWorldSpan searchAtpCode = null;
    // the all contract routing
    private ArrayList _AtpCodeFare = ArrayList.Synchronized(new ArrayList());
    // Set the Watch WorldSpan if it return result 
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WatchGuard"); public ArrayList AtpCodeFare
    {
    get
    {
    return _AtpCodeFare;
    }
    set
    {
    _AtpCodeFare = value;
    }
    } public AtpCodeThreadSearch(ArrayList sortedFil, SearchWorldSpan searchAtpCode)
    {
    this.sortedFil = tempSortedFil =sortedFil;
    this.searchAtpCode = searchAtpCode;
    } public void MutiThreadSearch()
    {
    while( true )
    {
    if ( sortedFil.Count == 0 )
    {
    break;
    } AbstractSearchStrategy.DbConnection = new SqlConnection(SearchFactory.DBConnection);
    AbstractSearchStrategy.DbConnection.Open();

    try
    {
    FarInfoResponse fare = null;
    if ( sortedFil.Count > 0 )
    {
    mut.WaitOne();
    fare = (FarInfoResponse)sortedFil.GetRange(0,1)[0];
    sortedFil.RemoveAt(0);
    mut.ReleaseMutex();
    }
    else
    break; //Routings
    ArrayList temp = (ArrayList)searchAtpCode.GetSearchResult(fare,tempSortedFil);

    mut.WaitOne();
    if(temp != null && temp.Count > 0)
    {
    AtpCodeFare.AddRange(temp);     
    }
    mut.ReleaseMutex();
    }
    catch(Exception Ex)
    {
    log.Error(Ex.Message,Ex); 
    mut.ReleaseMutex();
    }
    finally
    {
    AbstractSearchStrategy.DbConnection.Close();
    }
    }
    }
    }
    线程的调用代码:
    、、、、、、、、
    int ThreadNumber = Environments.ThreadNumber; 
    Thread[] MutiThread = new Thread[ThreadNumber];
    AtpCodeThreadSearch mutiThread  = new AtpCodeThreadSearch(sortedFil,this);

    for (int i = 0; i < ThreadNumber; i++) 

    MutiThread[i] = new Thread(new ThreadStart(mutiThread.MutiThreadSearch)); 
    MutiThread[i].Name = "AtpCode Thread " + i.ToString(); 
    MutiThread[i].Start(); 
    }  for(int i = 0; i< ThreadNumber; i++)
    {
    MutiThread[i].Join();
    } srl = mutiThread.AtpCodeFare;、、、、、、、、如果那位需要我详细的写一个给你。