How to correct share data between threads?

Konstantin Kutsevalov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 19 09:29:30 PST 2016


I need to receiving data in main thread and send its to other 
thread for processing. There is a simple (but wrong) code for 
example.
What need I to change to make it correct?


```
import std.stdio, std.string, std.array, core.thread, 
std.datetime, std.conv;

int main() {
	Pumpurum pp = new Pumpurum();
	Thread ppt = new Thread(&pp.processingData);
	ppt.start();
	while(pp.waitData())
	{
		// some operations may be
	}
	writeln("finished main");
	return 0;
}

class Pumpurum
{
	private string[string] Data;
	
	private string[string] Result;
	
	private bool _quit = false;
	
	private int _counter = 0;
	
	bool waitData()
	{
		// waits for new data and adds to Data
		string key;
		string line = readln(); // just for example, in real its will 
be data from several socket connections
		if (line !is null) {
			if (line == "quit\n") {
				this._quit = true;
				return false;
			}
			key = Clock.currTime().toString() ~ " " ~ 
to!string(this._counter);
			this.Data[key] = line; // adds new data to "Data"
		}
		return true;
	}
	
	void processingData()
	{
		string key, value;
		while(!this._quit) {
			if (this.Data.length > 0) {
				// todo checks the "Data" for some data, processing its and 
saves a result to "Result"
				foreach (key, value; this.Data) {
					writeln(value); // some processing :)
					this.Result[key] = value;
					this.Data.remove(key);
				}
			}
		}
		writeln("finished processing");
	}
	
}
```

Any advice may help. Thank you.


More information about the Digitalmars-d-learn mailing list