www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Share array element between threads

reply "Misu" <misugi-pwnu live.fr> writes:
Hi,

when I execute this code I have 7 7 7 as result, I think I 
understand why.

How can I execute a special task for one element ?

import std.stdio;
import std.parallelism;

void main(string[] args)
{
	class Account
	{
		public this(int id) { this.id = id; }
		int id;
	}

	Account[] accounts = [new Account(5), new Account(6), new 
Account(7)];

	foreach(acc; accounts)
	{
		task(() { writeln(acc.id); }).executeInNewThread();
	}
	
	readln();
}
Nov 06 2014
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Misu:

 void main(string[] args)
 {
 	class Account
 	{
 		public this(int id) { this.id = id; }
 		int id;
 	}
 ...
This is not an answer to your question, but note: void main() { class Foo {} static class Bar {} pragma(msg, __traits(classInstanceSize, Foo)); pragma(msg, __traits(classInstanceSize, Bar)); } Output: 12u 8u Bye, bearophile
Nov 06 2014
prev sibling parent reply "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm gmx.net> writes:
On Thursday, 6 November 2014 at 10:53:32 UTC, Misu wrote:
 Hi,

 when I execute this code I have 7 7 7 as result, I think I 
 understand why.

 How can I execute a special task for one element ?

 import std.stdio;
 import std.parallelism;

 void main(string[] args)
 {
 	class Account
 	{
 		public this(int id) { this.id = id; }
 		int id;
 	}

 	Account[] accounts = [new Account(5), new Account(6), new 
 Account(7)];

 	foreach(acc; accounts)
 	{
 		task(() { writeln(acc.id); }).executeInNewThread();
 	}
 	
 	readln();
 }
It's a bug: https://issues.dlang.org/show_bug.cgi?id=2043 As a workaround, you can nest the call in another lambda: foreach(acc; accounts) { (Account acc) { task(() { writeln(acc.id); }).executeInNewThread(); } (acc); }
Nov 06 2014
parent "Misu" <misugi-pwnu live.fr> writes:
On Thursday, 6 November 2014 at 13:04:18 UTC, Marc Sch├╝tz wrote:
 It's a bug: https://issues.dlang.org/show_bug.cgi?id=2043

 As a workaround, you can nest the call in another lambda:

     foreach(acc; accounts)
     {
         (Account acc) {
             task(() { writeln(acc.id); }).executeInNewThread();
         } (acc);
     }
Ok that's good. thank you !
Nov 06 2014