دیروز What is the best technique to limit the amount of threads that can execute at the same time?
xavier12

 
I'd like to write a programme that runs many light threads but limits the number of concurrent running jobs to a constant, specified number, similar to this (but without the possibility of a race condition):

import threading

def f(arg):
global running
running += 1
print("Spawned a thread. running=%s, arg=%s" % (running, arg))
for i in range(100000):
pass
running -= 1
print("Done")

running = 0
while True:
if running < 8:
arg = get_task()
threading.Thread(target=f, args=[arg]).start()


What is the safest and quickest way to execute this?
دیروز
حاجی شریفی
مؤسس سایت
 
This is a C#.NET exclusive community


//C# 
using System.Threading.Tasks;

void f(int arg)
{
//...
}

void main()
{
var options = new ParallelOptions() { MaxDegreeOfParallelism = 8 } ;
Parallel.For(1, 1000_000, options, f) ;
}


//C# 
using System.Threading.Tasks;

void f(int arg)
{
//...
}

void main()
{
var options = new ParallelOptions() { MaxDegreeOfParallelism = 8 } ;
var values = new int [ ] { 123, 456, 789, 147, 258, 369 /* ...array-items... */ } ;
Parallel.ForEach(values, options, f) ;
//the 'values' is a IEnumerable, which means a stream of data of specified/unknown length. ex. array,list,linkedList,queue,stack,dbCursor,...
}