Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / lazarus / 2010-09

Threads in Lazarus code base

113 messages · 22 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Juha Manninen gmail

Hi

I thought first to send this to Lazarus dev list but it may have wider interest so I send it here.

I am going to commit a patch for converter (=part of Lazarus code base) that uses TThread. It caches some unit paths in backround so that the converter settings dialog appears without delay. After the dialog I just "Thread.WaitFor" before starting the conversion. No other synchronization is needed. It is a perfect case for using a thread.

Under Linux I got a RunError. I know what it means, I need to use cthreads. In lazarus.pp unit I found:

  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}

so I rebuilt Lazarus with -dUseCThreads. Now it works perfectly!

Question: why is there need for "UseCThreads" define. Isn't cthreads needed always when using a *nix system? So, can I change the definition to :

  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}

If I now commit my code as it is, there will be complaints from people who run the converter under Linux for example.

I was amazed that there isn't a single use of threads in Lazarus code base. Threads however are the thing of the future because computers have more and more CPU cores. Threads are a way to utilize them.

Juha

Reply by email

Michael Van Canneyt
to Juha Manninen gmail
Juha Manninen wrote
I was amazed that there isn't a single use of threads in Lazarus code base. Threads however are the thing of the future because computers have more and more CPU cores. Threads are a way to utilize them.

Threads are a thing of the past as well. I've been programming threads since years. There is nothing exciting about them, mostly they are a pain.

Programming threads is error-prone, and needs careful design of your classes. I doubt that the lazarus IDE is very thread-safe, and therefor I think that the lazarus devels do not enable threading by default.

This is also why the UseCThreads is there. There is no need to drag in thread support if you don't use it: it creates additional dependencies which you simply don't need if you don't program using threads.

Michael.

Reply by email

Juha Manninen gmail
to Michael Van Canneyt
Michael Van Canneyt wrote
Threads are a thing of the past as well. I've been programming threads since years. There is nothing exciting about them, mostly they are a pain.

Correct but now there is no better way to implement parallelism. I know some languages have new syntax for it which is actually exciting. Maybe some day FPC will support such syntax but that is future. Now is now.

Show quoted text 7 lines
Programming threads is error-prone, and needs careful design of your classes. I doubt that the lazarus IDE is very thread-safe, and therefor I think that the lazarus devels do not enable threading by default. This is also why the UseCThreads is there. There is no need to drag in thread support if you don't use it: it creates additional dependencies which you simply don't need if you don't program using threads.

Yes but now I want to use it. I don't care if other parts of the IDE are "thread-safe". My thread is running only when the user is reading one settings dialog and it is done in a safe way. It simply makes the program better.

What would you suggest? How to commit the code so that we don't get complaints about RunErrors?

Juha

Reply by email

Michael Van Canneyt
to Juha Manninen gmail
Juha Manninen wrote 7 lines
On Wednesday 15 September 2010 11:48:09 Michael Van Canneyt wrote: > Threads are a thing of the past as well. I've been programming threads > since years. There is nothing exciting about them, mostly they are a pain. Correct but now there is no better way to implement parallelism. I know some languages have new syntax for it which is actually exciting. Maybe some day FPC will support such syntax but that is future. Now is now.

Well...
IMHO the whole threading model is basically flawed, but currently there is no other alternative. At least not in any language I know.

Show quoted text 14 lines
> Programming threads is error-prone, and needs careful design of your > classes. I doubt that the lazarus IDE is very thread-safe, and therefor I > think that the lazarus devels do not enable threading by default. > > This is also why the UseCThreads is there. There is no need to drag in > thread support if you don't use it: it creates additional dependencies > which you simply don't need if you don't program using threads. Yes but now I want to use it. I don't care if other parts of the IDE are "thread-safe". My thread is running only when the user is reading one settings dialog and it is done in a safe way. It simply makes the program better. What would you suggest? How to commit the code so that we don't get complaints about RunErrors?

This is a question the lazarus devels must answer. I just provided a possible hypothesis why currently they don't use it :-)

Michael.

Reply by email

Marc Weustink
to Michael Van Canneyt
Michael Van Canneyt wrote 39 lines
On Wed, 15 Sep 2010, Juha Manninen (gmail) wrote: > On Wednesday 15 September 2010 11:48:09 Michael Van Canneyt wrote: >> Threads are a thing of the past as well. I've been programming threads >> since years. There is nothing exciting about them, mostly they are a >> pain. > > Correct but now there is no better way to implement parallelism. I > know some > languages have new syntax for it which is actually exciting. Maybe > some day > FPC will support such syntax but that is future. Now is now. Well... IMHO the whole threading model is basically flawed, but currently there is no other alternative. At least not in any language I know. >> Programming threads is error-prone, and needs careful design of your >> classes. I doubt that the lazarus IDE is very thread-safe, and >> therefor I >> think that the lazarus devels do not enable threading by default. >> >> This is also why the UseCThreads is there. There is no need to drag in >> thread support if you don't use it: it creates additional dependencies >> which you simply don't need if you don't program using threads. > > Yes but now I want to use it. I don't care if other parts of the IDE are > "thread-safe". My thread is running only when the user is reading one > settings > dialog and it is done in a safe way. It simply makes the program better. > > What would you suggest? How to commit the code so that we don't get > complaints > about RunErrors? This is a question the lazarus devels must answer. I just provided a possible hypothesis why currently they don't use it :-)

In my experience, if you don't need them don't use them just for the fun of it. This makes coding and debugging way easier.

In case of lazarus, what do you want to do in a thread ?

Marc

Reply by email

Vincent Snijders
to Juha Manninen gmail: Hi I thought first to send this to Lazarus dev list but it may have wider interest so I…

2010/9/15 Juha Manninen (gmail) :

Show quoted text 9 lines
Question: why is there need for "UseCThreads" define. Isn't cthreads needed always when using a *nix system? So, can I change the definition to : ?{$IFDEF UNIX} ?cthreads, ?{$ENDIF} If I now commit my code as it is, there will be complaints from people who run the converter under Linux for example.

By default Lazarus is a single threaded application. Only if a lazarus packages that uses threads is used, the IDE needs to include the cthreads unit. Such packages add -dUseCThreads in their usage options (Open package, Options -> Usage -> Add options to dependent packages and projects -> Custom).

So, no, it is not always needed, until now, only if a third party package requires it. I would think twice about making this change.

Vincent

Reply by email

Michael Schnell
to Michael Van Canneyt: Threads are a thing of the past as well. I've been programming threads since years. There…
Michael Van Canneyt wrote
Threads are a thing of the past as well. I've been programming threads since years. There is nothing exciting about them, mostly they are a pain.

OK, but

how do you make a program that is able to non sluggishly communicate with the user while performing decent work (without doing performance-killing polling stuff like "process Messages") ?

how do you make a program doing huge calculations use multiple CPUs which are the contrary of "of the past" ?

-Michael

Reply by email

Michael Schnell
to Michael Van Canneyt: Well... IMHO the whole threading model is basically flawed, but currently there is no…
Michael Van Canneyt wrote
Well... IMHO the whole threading model is basically flawed, but currently there is no other alternative. At least not in any language I know.

Delphi Prism does know "parallel" loops and several related constructs.

Here the .NET or Mono framework does the dirty job converting this into OS threads, but the RTL _could_ be enhanced to do this, as well, supposedly even in a quite Prism compatible way.

-Michael

Reply by email

Michael Schnell
to Juha Manninen gmail
Juha Manninen wrote 5 lines
On Wednesday 15 September 2010 13:32:20 Michael Schnell wrote: > Maybe you could start an external process for this .... ... and pass the data with temporary text files? Why would I do that? A thread is lighter, it can see the variables I already defined, it is easier to synchronize (WaitFor in this case)...

Linux is very good with passing data via pipes. stdout is always present and can be captured by the parent process. This in fact is the "Unix way" to do those things (rather than using Threads). But I am sure it can be done with windows and Mac, too.

What is wrong with threads?

Nothing. It's just error-prone. Enabling CThreads slightly reduces the overall performance, but I don't think it's relevant.

-Michael

Reply by email

Michael Van Canneyt
to Michael Schnell: OK, but how do you make a program that is able to non sluggishly communicate with the…
Michael Schnell wrote 10 lines
On 09/15/2010 10:48 AM, Michael Van Canneyt wrote: > > Threads are a thing of the past as well. I've been programming threads > since years. > There is nothing exciting about them, mostly they are a pain. OK, but how do you make a program that is able to non sluggishly communicate with the user while performing decent work (without doing performance-killing polling stuff like "process Messages") ?

What is so performance killing about process messages ?

What do you think the OS does when switching threads ? A thread switch is much more expensive than a "process messages".

how do you make a program doing huge calculations use multiple CPUs which are the contrary of "of the past" ?

I didn't claim to have a better solution.
I just observed that the very idea of threads is basically flawed.

These are not my words, but the conclusion of scientific research on the subject.

Michael.

Reply by email

Juha Manninen gmail
to Vincent Snijders: 2010/9/15 Juha Manninen (gmail) : By default Lazarus is a single threaded application.…
Vincent Snijders wrote 8 lines
By default Lazarus is a single threaded application. Only if a lazarus packages that uses threads is used, the IDE needs to include the cthreads unit. Such packages add -dUseCThreads in their usage options (Open package, Options -> Usage -> Add options to dependent packages and projects -> Custom). So, no, it is not always needed, until now, only if a third party package requires it. I would think twice about making this change.

Ok, I will check the OnIde handler solution you suggested in the other mail. Then the dialog would appear immediately and the user would propably not notice anything because he typically thinks for a second before clicking anything, and during that time the scanning task is completed already. Still, it is not an ideal solution. Sometimes an "experienced converter user" would click a control quickly and then send a bug report about the dialog not responding always.

I would understand this resistance against threads if there was a technical reason for it. Threads in FPC/Lazarus are working well for there some technical reason I don't know about?

The main trend in programming now is to encourage threading, not to ban it. I am little puzzled...

Juha

Reply by email

Graeme Geldenhuys
to Juha Manninen gmail: ... and pass the data with temporary text files? Why would I do that? A thread is…
Juha Manninen wrote 8 lines
On Wednesday 15 September 2010 13:32:20 Michael Schnell wrote: > ? Maybe you could start an external process for this .... ... and pass the data with temporary text files? Why would I do that? A thread is lighter, it can see the variables I already defined, it is easier to synchronize (WaitFor in this case)... What is wrong with threads?

Juha, I fully agree with you. I also can't believe Lazarus is single threaded. I know of *many* areas where multiple threads could make Lazarus a lot more "snappy"!

The questions should rather be "why must we not use threads"? With all the the multi-core CPU's out there, and all the background tasks the IDE could do - staying single thread is rather daft.

I use multiple threads all the time in our software. Yes it's an "advanced" feature of the language, so you need to know what you are doing. But I thought a IDE would qualify as an "advanced application"
- after all, it's slightly more code than a "hello world" app. :-) I would expect the developers that work on the IDE, to also be "advanced developers" with a bit more know-how than newbies to the Object Pascal language.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Juha Manninen gmail
to Michael Schnell: Linux is very good with passing data via pipes. stdout is always present and can be…
Michael Schnell wrote
Linux is very good with passing data via pipes. stdout is always present and can be captured by the parent process. This in fact is the "Unix way" to do those things (rather than using Threads). But I am sure it can be done with windows and Mac, too.

Anyway, it doesn't sound very easy for a crossplatform solution. Besides, I don't want to start any external tool. I want to run a rather short function in my code. A thread is perfect for doing that.

Nothing. It's just error-prone. Enabling CThreads slightly reduces the overall performance, but I don't think it's relevant.

Ok, so there is a technical reason against threads, a performance hit. I didn't know.

Juha

Reply by email

Graeme Geldenhuys
to Michael Schnell
Michael Schnell wrote
I suppose the GUI will not ?react while the task you run in "OnIdle" is busy. So you will need to split your add-on in tiny pieces and run one after the other in subsequent "OnIdle" callbacks.

Or use a thread and make the code simpler! :)

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Graeme Geldenhuys
to Juha Manninen gmail: Anyway, it doesn't sound very easy for a crossplatform solution. Besides, I don't want to…

On 15 September 2010 13:07, Juha Manninen (gmail) >> Nothing. It's just error-prone. Enabling CThreads slightly reduces the

> overall performance, but I don't think it's relevant. Ok, so there is a technical reason against threads, a performance hit. I didn't know.

I would like to see performance tests and clear results on that, before I believe it! There are so many apps out there (and more every day) that use multiple thread. Yes the threading implementation in Delphi/Free Pascal is not perfect, but it's a damn site better than clunky OnIdle event handlers and external processes and pipes etc. to try and achieve the same task as a simple thread would do.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Michael Schnell
to Juha Manninen gmail: Anyway, it doesn't sound very easy for a crossplatform solution. Besides, I don't want to…
Juha Manninen wrote
Anyway, it doesn't sound very easy for a crossplatform solution.

Only because a (well accepted) platform-independent infrastructure is lacking. FPC does come with a lot of platform independent stuff like TThread, TEvent, TCriticalSection and SyncOBJs. Even ProcessMessages, "Procedure...Message" and Sending Messages is provided in a platform independent dent ways (mimicking the Windows API or thread synchronization even in Linux/Mac).

-Michael

Reply by email

Graeme Geldenhuys
to Juha Manninen gmail: Ok, I will check the OnIde handler solution you suggested in the other mail. Then the…

On 15 September 2010 13:00, Juha Manninen (gmail)

The main trend in programming now is to encourage threading, not to ban it. I am little puzzled...

+1
As I said, threading is an "advanced" feature, and clearly here are many developers that are afraid of something they don't understand, so simply think banning the feature is the solution. Simply learn multi-threading, get some experience with it, then using threads are not a problem. It's the same deal as using Pointers. If you don't know what you are doing, you are f**ked.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Vincent Snijders
to Graeme Geldenhuys

2010/9/15 Graeme Geldenhuys :

Show quoted text 12 lines
On 15 September 2010 13:00, Juha Manninen (gmail) > > The main trend in programming now is to encourage threading, not to ban it. > I am little puzzled... +1 As I said, threading is an "advanced" feature, and clearly here are many developers that are afraid of something they don't understand, so simply think banning the feature is the solution. Simply learn multi-threading, get some experience with it, then using threads are not a problem. It's the same deal as using Pointers. If you don't know what you are doing, you are f**ked.

IMHO, debugging Lazarus is hard as it is, why make it more complicated by turning it in a mulithtreaded app. That said, there is information in the wiki about debugging mulithreaded applications (http://wiki.lazarus.freepascal.org/Multithreaded_Application_Tutorial#Linux) and I am not the one developing on Linux, so I don't care that much.

Vincent

Reply by email

Mattias Gaertner
to Graeme Geldenhuys: Juha, I fully agree with you. I also can't believe Lazarus is single threaded. I know of…
Show quoted text 13 lines
On 15 September 2010 12:38, Juha Manninen (gmail) wrote: > On Wednesday 15 September 2010 13:32:20 Michael Schnell wrote: >> ? Maybe you could start an external process for this .... > > ... and pass the data with temporary text files? > Why would I do that? A thread is lighter, it can see the variables I already > defined, it is easier to synchronize (WaitFor in this case)... > > What is wrong with threads? Juha, I fully agree with you. I also can't believe Lazarus is single threaded. I know of *many* areas where multiple threads could make Lazarus a lot more "snappy"!

True. And I have already plans to use some threads.

The questions should rather be "why must we not use threads"? With all the the multi-core CPU's out there, and all the background tasks the IDE could do - staying single thread is rather daft.

Threads have several disadvantages:
*They are harder to debug,
*it is harder to follow the program flow,
*you have to program carefully to avoid dead lock and non exclusive access, which is especially hard where design time packages extends the code base,
*many IDE parts will become slower (once you start a thread the RTL uses critical sections and especially string handling become much slower).

Show quoted text 7 lines
I use multiple threads all the time in our software. Yes it's an "advanced" feature of the language, so you need to know what you are doing. But I thought a IDE would qualify as an "advanced application" - after all, it's slightly more code than a "hello world" app. :-) I would expect the developers that work on the IDE, to also be "advanced developers" with a bit more know-how than newbies to the Object Pascal language.

Yes, and there is a golden rule:
Before doing threads, always try first to do it good single threaded. Many things can be done on idle. In fact the IDE does many things on idle, for example the code explorer, the fpdoc editor, the code hints, the code browser. These work in small steps.

Juha: scanning unit paths can be done on idle too. Of course when searching a network the waits can be quite long, and then another thread/process is needed.

Mattias

Reply by email

Michael Van Canneyt
to Juha Manninen gmail: ... and pass the data with temporary text files? Why would I do that? A thread is…
Juha Manninen wrote 8 lines
On Wednesday 15 September 2010 13:32:20 Michael Schnell wrote: > Maybe you could start an external process for this .... ... and pass the data with temporary text files? Why would I do that? A thread is lighter, it can see the variables I already defined, it is easier to synchronize (WaitFor in this case)... What is wrong with threads?

Most programs and algorithms are not thread safe.

So if you start introducing threads, that means that there are a lot more things that can start going wrong, introducing an extra maintenance burden on the Lazarus team.

I'm not saying that your code *will* cause things to go wrong;
But once the door is open...

Michael.

Reply by email

Henry Vermaak
to Graeme Geldenhuys: Or use a thread and make the code simpler! :) ? - Graeme -…
Graeme Geldenhuys wrote 7 lines
On 15 September 2010 13:07, Michael Schnell wrote: > > I suppose the GUI will not ?react while the task you run in "OnIdle" is > busy. So you will need to split your add-on in tiny pieces and run one after > the other in subsequent "OnIdle" callbacks. Or use a thread and make the code simpler! :)

And more error prone, and open to races and deadlocks, and harder to debug. Imho, using threads are for serious work and code that needs to take advantage of extra cores/processors.

Henry

Reply by email

Mattias Gaertner
to Vincent Snijders: 2010/9/15 Juha Manninen (gmail) : I suggest: Don't use threads, but take a look at the…
Show quoted text 8 lines
2010/9/15 Juha Manninen (gmail) : > What would you suggest? How to commit the code so that we don't get complaints > about RunErrors? I suggest: Don't use threads, but take a look at the code browser, how to quickly show a dialog, while information is still being gathered. I think it uses an OnIde handler.

Yes. You can even change the search fields and the search will adapt while you type. This is done by splitting the search into small steps. A multi threaded implementation would do the same, but you would need some extra thread control (e.g. critical sections) and all other IDE code accessing the structures must be adapted too. OTOH a multi threaded might start several threads which might be faster, although the speed is mainly limited by disk and memory throughput, not so much by cpu. A big time (two seconds) is spent in putting the 200.000 nodes into a TTreeView. This can not be multi threaded. TTreeView needs some optimizations to not compute all the text widths every time.

Mattias

Reply by email

Mark Morgan Lloyd
to Juha Manninen gmail: Hi I thought first to send this to Lazarus dev list but it may have wider interest so I…
Juha Manninen wrote
so I rebuilt Lazarus with -dUseCThreads. Now it works perfectly! Question: why is there need for "UseCThreads" define. Isn't cthreads needed always when using a *nix system?

Threads have been stable on x86 Linux for a few years, but rather less so on some other processors if I remember correctly. Also I don't know what the situation is for other unix implementations such as Solaris. I'd suggest that you not make any changes that rely on having threads available: having an optional enhancement that can benefit from them is a different matter.

Furthermore, I'd note that Lazarus is an IDE, and as such is overwhelmingly visual. While there is any possibility that Lazarus itself or the underlying widget sets and GUI implementations are not entirely thread-safe, I think that any mandatory adoption of threads should be attempted with extreme caution.

Having said that, it'll have to be done sometime. But tracking down thread-related problems is extremely difficult, and I'm certainly not the one who's going to risk breaking things.

Mark Morgan Lloyd markMLl .AT. telemetry.co .DOT. uk [Opinions above are the author's, not those of his employers or colleagues]

Reply by email

Mattias Gaertner
to Michael Van Canneyt: What is so performance killing about process messages ? What do you think the OS does…
Show quoted text 19 lines
On Wed, 15 Sep 2010, Michael Schnell wrote: > On 09/15/2010 10:48 AM, Michael Van Canneyt wrote: >> >> Threads are a thing of the past as well. I've been programming threads >> since years. >> There is nothing exciting about them, mostly they are a pain. > OK, but > > how do you make a program that is able to non sluggishly communicate with the > user while performing decent work (without doing performance-killing polling > stuff like "process Messages") ? What is so performance killing about process messages ? What do you think the OS does when switching threads ? A thread switch is much more expensive than a "process messages".

Threads are not bad per se.
Just the implementation in many common languages are bad. There are better designs since more than 20 years, but programmers are used to think single threaded, so the ideas never got a hype.

Show quoted text 7 lines
> how do you make a program doing huge calculations use multiple CPUs which are > the contrary of "of the past" ? I didn't claim to have a better solution. I just observed that the very idea of threads is basically flawed. These are not my words, but the conclusion of scientific research on the subject.

+1

Mattias

Reply by email

Mattias Gaertner
to Juha Manninen gmail: Ok, I will check the OnIde handler solution you suggested in the other mail. Then the…
Show quoted text 17 lines
On Wednesday 15 September 2010 12:42:58 Vincent Snijders wrote: > By default Lazarus is a single threaded application. Only if a lazarus > packages that uses threads is used, the IDE needs to include the > cthreads unit. Such packages add -dUseCThreads in their usage options > (Open package, Options -> Usage -> Add options to dependent packages > and projects -> Custom). > > So, no, it is not always needed, until now, only if a third party > package requires it. I would think twice about making this change. Ok, I will check the OnIde handler solution you suggested in the other mail. Then the dialog would appear immediately and the user would propably not notice anything because he typically thinks for a second before clicking anything, and during that time the scanning task is completed already. Still, it is not an ideal solution. Sometimes an "experienced converter user" would click a control quickly and then send a bug report about the dialog not responding always.

Show a progress bar.
Enable the button not before it is ready.

Show quoted text 6 lines
I would understand this resistance against threads if there was a technical reason for it. Threads in FPC/Lazarus are working well for me at least. Is there some technical reason I don't know about? The main trend in programming now is to encourage threading, not to ban it. I am little puzzled...

Multi threading is not banned. Just keep in mind that it is a magnitude harder to maintain and add comments to every method/variable if it runs in the main thread or a worker thread.

Mattias

Reply by email

Mattias Gaertner
to Michael Schnell: I suppose the GUI will not react while the task you run in "OnIdle" is busy. So you will…
Show quoted text 7 lines
On 09/15/2010 01:00 PM, Juha Manninen (gmail) wrote: > Ok, I will check the OnIde handler solution Hmm, I suppose the GUI will not react while the task you run in "OnIdle" is busy. So you will need to split your add-on in tiny pieces and run one after the other in subsequent "OnIdle" callbacks.

You must do that for the worker thread too, otherwise you can not cancel it without delay.

Mattias

Reply by email

Mattias Gaertner
to Henry Vermaak: And more error prone, and open to races and deadlocks, and harder to debug. Imho, using…
Show quoted text 12 lines
On 15 September 2010 12:09, Graeme Geldenhuys wrote: > On 15 September 2010 13:07, Michael Schnell wrote: >> >> I suppose the GUI will not ?react while the task you run in "OnIdle" is >> busy. So you will need to split your add-on in tiny pieces and run one after >> the other in subsequent "OnIdle" callbacks. > > Or use a thread and make the code simpler! :) And more error prone, and open to races and deadlocks, and harder to debug. Imho, using threads are for serious work and code that needs to take advantage of extra cores/processors.

+1

Mattias

Reply by email

Michael Schnell
to Michael Van Canneyt: What is so performance killing about process messages ? What do you think the OS does…
Michael Van Canneyt wrote
What is so performance killing about process messages ?

process message is a function call that obviously take some microseconds to run. Thus, if you do it very often, it degrades the overall performance, if you do it rather seldom, the latency of the other tasks the program needs to do degrades

What do you think the OS does when switching threads ? A thread switch is much more expensive than a "process messages".

Of course the OS needs much more time to switch threads than process messages needs "program tasks". But the OS does not need to do polling. Threads are only switched when needed while process messages needs to be called very frequently for a decent latency and nearly all calls are in vain.

Show quoted text 6 lines
> how do you make a program doing huge calculations use multiple CPUs > which are the contrary of "of the past" ? I didn't claim to have a better solution. I just observed that the very idea of threads is basically flawed.

That is why I started my answer with "OK" .)

These are not my words, but the conclusion of scientific research on the subject.

There are several decent scientific research papers that bash threads. ("Migrating away from threads has been mentioned here recently for it's neat practical usefulness.)

My impression is that regarding the OS-interface of a program that needs the said features (multiple "logical threads", performance, latency, making use of modern SMP systems, ...), threads are a necessity. But programming languages might be able to in many cases hide the dirty details from the programmer (e.g. "parallel" loops, see the Delphi Prism and/or .NET documentation on these issues.) If FPC could be enhances tn that direction it might be a decent improvement.

-Michael

Reply by email

Michael Schnell
Juha Manninen wrote
+1 I would love that!

:) (This already has been discussed here some months ago.)

I feel that this non-trivial performance-targeting project should not be started before (as discussed recently) the libc binding of the TThread implementation has been removed and by that a faster threadvar implementation is in place.

-Michael

Reply by email

Juha Manninen gmail
to Michael Van Canneyt: Most programs and algorithms are not thread safe. So if you start introducing threads,…
Michael Van Canneyt wrote 8 lines
Most programs and algorithms are not thread safe. So if you start introducing threads, that means that there are a lot more things that can start going wrong, introducing an extra maintenance burden on the Lazarus team. I'm not saying that your code *will* cause things to go wrong; But once the door is open...

Yes, I understand the problems that extensive use of threads can cause.

However in this case it is safe because the thread is running in parallel with a modal dialog and the rest of Lazarus is doing nothing. Also, the thread can freely access the variables it needs, there is no interaction with the dialog. It only runs in parallel with it. The thread does not continue after the dialog closes (hence WaitFor).
This kind of usage improves the user experience even with 1 CPU core.

Another good use for threads is splitting a loop into parallel sections. I actually used the MultiThreadProcs package. It is a cool piece of SW. This improves performance with many CPU cores.

Totally banning threads is not right, IMO. Of course one has to be careful with them, but that's what programming is about. It is not for sloppy people.

Juha

Reply by email

Michael Schnell
to Michael Schnell: Only because a (well accepted) platform-independent infrastructure is lacking. FPC does…
Michael Schnell wrote
, "Procedure...Message" and Sending Messages ...

Sorry for the misleading comment.

Of course while "Procedure Message" is a language construct and thus basically implemented in FPC, sending Messages is implemented in the LCL and only available when using a "Widget Type" that supports it.

This is because Windows provides the message queue and does not need an implementation in the library, while Linux and MacOS don't provide a message queue and thus the Message queue is implemented in the LCL code. Here GUI callbacks are used to feed the GUI messages to the queue.

IMHO, it would be better if a generic message queue would be implemented in the RTL and same would be replaced or enhanced by the LCL according to the Widget Type used. With this any Widget Type would have a message Queue out of the box.

-Michael

Reply by email

ik
to Michael Schnell: process message is a function call that obviously take some microseconds to run. Thus, if…
Michael Schnell wrote 29 lines
On 09/15/2010 12:46 PM, Michael Van Canneyt wrote: > > What is so performance killing about process messages ? > process message is a function call that obviously take some microseconds to run. Thus, if you do it very often, it degrades the overall performance, if you do it rather seldom, the latency of the other tasks the program needs to do degrades > What do you think the OS does when switching threads ? A thread switch > is much more expensive than a "process messages". > Of course the OS needs much more time to switch threads than process messages needs "program tasks". But the OS does not need to do polling. Threads are only switched when needed while process messages needs to be called very frequently for a decent latency and nearly all calls are in vain. > how do you make a program doing huge calculations use multiple CPUs >> which are the contrary of "of the past" ? >> > > I didn't claim to have a better solution. I just observed that the > very idea of threads is basically flawed. > That is why I started my answer with "OK" .)

Gilad Ben Yosef gave a lecture about Process vs Threads last year : http://free-electrons.com/pub/video/2009/elce/elce2009-ben-yossef-threads-processes.ogv <http://free-electrons.com/pub/video/2009/elce/elce2009-ben-yossef-threads-processes.ogv%20>

I recommend to watch it.

Show quoted text 26 lines
> These are not my words, but the conclusion of scientific research on > the subject. > There are several decent scientific research papers that bash threads. ("Migrating away from threads has been mentioned here recently for it's neat practical usefulness.) My impression is that regarding the OS-interface of a program that needs the said features (multiple "logical threads", performance, latency, making use of modern SMP systems, ...), threads are a necessity. But programming languages might be able to in many cases hide the dirty details from the programmer (e.g. "parallel" loops, see the Delphi Prism and/or .NET documentation on these issues.) If FPC could be enhances tn that direction it might be a decent improvement. -Michael -- _______________________________________________ Lazarus mailing list http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100915/7cd0abd1/attachment-0001.html>

Reply by email

Michael Schnell
to Juha Manninen gmail: Yes, I understand the problems that extensive use of threads can cause. However in this…
Juha Manninen wrote
Totally banning threads is not right, IMO.

From an "OS View" threads are just processes only that the memory manager tables are common. So they are as useful as processes are and even a lot faster when it comes to transferring informations between the threads of a process. Only the programmers are having problems to handle this power :).

So it would be great to be able to use threads but to hide this from the programmers, (only very few programmers decently understand the use of "ThreadVar"). TThread does this hiding very bad. Parallel Loops might offer a more easy to use language based Thread model. I think there are some more such concepts around.

-Michael

Reply by email

Graeme Geldenhuys
to Mattias Gaertner: On Wed, 15 Sep 2010 13:05:40 +0200 True. And I have already plans to use some threads.…
Mattias Gaertner wrote
True. And I have already plans to use some threads.

Good to hear.

Threads have several disadvantages: *They are harder to debug,

debugging with FPC+GDB is already hard, so there would be no difference. ;-)

*it is harder to follow the program flow,

Same can be said for any event-based applications. Change a property here, and other things might execute elsewhere. Or if Lazarus debugging was extended (like MSEide can do), then you can monitor the value at a memory address for changes, and if a change occurs, a breakpoint is triggered - at which point you can call up the call stack to see what code changed that value. This feature is called "watchpoints", and it works brilliantly in MSEide.

*you have to program carefully to avoid dead lock and non exclusive access, which is especially hard where design time packages extends the code base,

Try and use the TMultiReadExclusiveWriteSynchronizer instead. At least you will not block threads that only want to do reading (which seem to be most of the IDE task you mentioned with the OnIdle comment).

*many IDE parts will become slower (once you start a thread the RTL uses critical sections and especially string handling become much slower).

See previous point.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Graeme Geldenhuys
to Michael Schnell
Michael Schnell wrote 5 lines
> > This feature is called "watchpoints", and it works brilliantly in MSEide. Watchpoints are a normal feature of gdb. So why should Lazarus not be able to support it ?

I not saying Lazarus can't support it, I am saying Lazarus doesn't currently support it. If Lazarus did, it will make it easier to debug event-based and multi-threaded apps (like I have experienced under MSEide).

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Florian Klaempfl
to Michael Schnell: process message is a function call that obviously take some microseconds to run. Thus, if…
Michael Schnell wrote 7 lines
My impression is that regarding the OS-interface of a program that needs the said features (multiple "logical threads", performance, latency, making use of modern SMP systems, ...), threads are a necessity. But programming languages might be able to in many cases hide the dirty details from the programmer (e.g. "parallel" loops, see the Delphi Prism and/or .NET documentation on these issues.) If FPC could be enhances tn that direction it might be a decent improvement.

The parallel loop solves nothing which makes threading hard and is only a cheap excuse. The real problems of threading are synchronization and especially abording threads e.g. triggered by the main thread.

Reply by email

ik
to Florian Klaempfl
Florian Klaempfl wrote 13 lines
Am 15.09.2010 13:56, schrieb Michael Schnell: > My impression is that regarding the OS-interface of a program that needs > the said features (multiple "logical threads", performance, latency, > making use of modern SMP systems, ...), threads are a necessity. But > programming languages might be able to in many cases hide the dirty > details from the programmer (e.g. "parallel" loops, see the Delphi Prism > and/or .NET documentation on these issues.) If FPC could be enhances tn > that direction it might be a decent improvement. The parallel loop solves nothing which makes threading hard and is only a cheap excuse. The real problems of threading are synchronization and especially abording threads e.g. triggered by the main thread.

So how do you do multiple sub routines "at the same time", or some tasks that will hang your system but you require it to function even when it does the heavy work ?
A new process is not that simple to do either.

Show quoted text 7 lines
-- _______________________________________________ Lazarus mailing list http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus

Ido
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100915/083dbef3/attachment.html>

Reply by email

Florian Klaempfl
to ik
ik wrote 25 lines
On Wed, Sep 15, 2010 at 15:16, Florian Klaempfl < <mailto:>> wrote: Am 15.09.2010 13:56, schrieb Michael Schnell: > My impression is that regarding the OS-interface of a program that needs > the said features (multiple "logical threads", performance, latency, > making use of modern SMP systems, ...), threads are a necessity. But > programming languages might be able to in many cases hide the dirty > details from the programmer (e.g. "parallel" loops, see the Delphi Prism > and/or .NET documentation on these issues.) If FPC could be enhances tn > that direction it might be a decent improvement. The parallel loop solves nothing which makes threading hard and is only a cheap excuse. The real problems of threading are synchronization and especially abording threads e.g. triggered by the main thread. So how do you do multiple sub routines "at the same time", or some tasks that will hang your system but you require it to function even when it does the heavy work ?

It depends on the application. But as I said before: aborting something like a parallel loop because the user pressed e.g. ESC isn't easy either.

Reply by email

Mattias Gärtner
to Florian Klaempfl: It depends on the application. But as I said before: aborting something like a parallel…

Zitat von Florian Klaempfl :

Show quoted text 29 lines
Am 15.09.2010 15:26, schrieb ik: > > > On Wed, Sep 15, 2010 at 15:16, Florian Klaempfl < > <mailto:>> wrote: > > Am 15.09.2010 13:56, schrieb Michael Schnell: > > My impression is that regarding the OS-interface of a program that > needs > > the said features (multiple "logical threads", performance, latency, > > making use of modern SMP systems, ...), threads are a necessity. But > > programming languages might be able to in many cases hide the dirty > > details from the programmer (e.g. "parallel" loops, see the Delphi > Prism > > and/or .NET documentation on these issues.) If FPC could be > enhances tn > > that direction it might be a decent improvement. > > The parallel loop solves nothing which makes threading hard and is only > a cheap excuse. The real problems of threading are synchronization and > especially abording threads e.g. triggered by the main thread. > > > So how do you do multiple sub routines "at the same time", or some tasks > that will hang your system but you require it to function even when it > does the heavy work ? It depends on the application. But as I said before: aborting something like a parallel loop because the user pressed e.g. ESC isn't easy either.

It's not that hard either.
Parallel loops/procedures are not as important as some compiler vendors are saying, but implemented in the compiler they can save a lot of type work and allow to reduce some overhead. The alternative is to create an IDE plugin to parallelize a loop as described here http://wiki.lazarus.freepascal.org/Parallel_procedures#Example:_Parallel_loop

Mattias

Reply by email

ik
to Florian Klaempfl: It depends on the application. But as I said before: aborting something like a parallel…
Florian Klaempfl wrote 34 lines
Am 15.09.2010 15:26, schrieb ik: > > > On Wed, Sep 15, 2010 at 15:16, Florian Klaempfl < > <mailto:>> wrote: > > Am 15.09.2010 13:56, schrieb Michael Schnell: > > My impression is that regarding the OS-interface of a program that > needs > > the said features (multiple "logical threads", performance, latency, > > making use of modern SMP systems, ...), threads are a necessity. But > > programming languages might be able to in many cases hide the dirty > > details from the programmer (e.g. "parallel" loops, see the Delphi > Prism > > and/or .NET documentation on these issues.) If FPC could be > enhances tn > > that direction it might be a decent improvement. > > The parallel loop solves nothing which makes threading hard and is only > a cheap excuse. The real problems of threading are synchronization and > especially abording threads e.g. triggered by the main thread. > > > So how do you do multiple sub routines "at the same time", or some tasks > that will hang your system but you require it to function even when it > does the heavy work ? It depends on the application. But as I said before: aborting something like a parallel loop because the user pressed e.g. ESC isn't easy either.

Here is a real thing I've made using threads (and a thread pool). I would be glad to know how to do it without it:
I have a PHP script that accept web service request. That's triggers a Ruby (that version 1.8x and bellow uses green threads) daemon to start a call into Asterisk PBX.

The thing is that I can have many requests at the same time. And I need to answer each request up to 3 seconds worst case.
If I have more then one request per second, how would you do it without threads or blocking the daemon in responding into additional requests "at the same time" ?

Show quoted text 8 lines
-- _______________________________________________ Lazarus mailing list http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus

Ido
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100915/c009411d/attachment.html>

Reply by email

Vincent Snijders
to Mattias Gärtner: Zitat von Florian Klaempfl : It's not that hard either. Parallel loops/procedures are not…

2010/9/15 Mattias G?rtner :

Show quoted text 6 lines
It's not that hard either. Parallel loops/procedures are not as important as some compiler vendors are saying, but implemented in the compiler they can save a lot of type work and allow to reduce some overhead. The alternative is to create an IDE plugin to parallelize a loop as described here http://wiki.lazarus.freepascal.org/Parallel_procedures#Example:_Parallel_loop

I wonder if the examples can be made more type safe by using the "is nested" syntax that is new in fpc 2.5.1. Google didn't find any docs about it. Is it available in mode objfpc or just in mode macpas?

Vincent

Reply by email

Florian Klaempfl
to Mattias Gärtner: Zitat von Florian Klaempfl : It's not that hard either. Parallel loops/procedures are not…
Mattias G?rtner wrote 38 lines
Zitat von Florian Klaempfl : > Am 15.09.2010 15:26, schrieb ik: >> >> >> On Wed, Sep 15, 2010 at 15:16, Florian Klaempfl < >> <mailto:>> wrote: >> >> Am 15.09.2010 13:56, schrieb Michael Schnell: >> > My impression is that regarding the OS-interface of a program that >> needs >> > the said features (multiple "logical threads", performance, >> latency, >> > making use of modern SMP systems, ...), threads are a >> necessity. But >> > programming languages might be able to in many cases hide the >> dirty >> > details from the programmer (e.g. "parallel" loops, see the Delphi >> Prism >> > and/or .NET documentation on these issues.) If FPC could be >> enhances tn >> > that direction it might be a decent improvement. >> >> The parallel loop solves nothing which makes threading hard and >> is only >> a cheap excuse. The real problems of threading are >> synchronization and >> especially abording threads e.g. triggered by the main thread. >> >> >> So how do you do multiple sub routines "at the same time", or some tasks >> that will hang your system but you require it to function even when it >> does the heavy work ? > > It depends on the application. But as I said before: aborting something > like a parallel loop because the user pressed e.g. ESC isn't easy either. It's not that hard either.

Well, it depends how much resources must be freed, how "snappy" the abording should be etc. If the parallel threads need also locking, it gets ugly imo.

Reply by email

Luiz Americo Pereira Camara
to Mattias Gaertner: On Wed, 15 Sep 2010 13:05:40 +0200 True. And I have already plans to use some threads.…
Mattias Gaertner wrote
*many IDE parts will become slower (once you start a thread the RTL uses critical sections and especially string handling become much slower).

If i understand correctly all program will suffer the performance hit, not only the "threaded" part, right?

Do you have an idea of how slower string handling would be?

I'm asking this because i'm planning to make a client of a REST service through http and i choose Synapse to do the communication.

Since Synapse recommends to use thread to avoid GUI freeze, i planned to use a thread for getting the data.

At the other side this REST server uses JSON as the data format.

If the thread really affects badly the string handling (and parsing JSON does a lot of it) i would rethink the strategy and go for an event based http client like lnet.

Luiz

Reply by email

David W Noon
to Marc Weustink: So let's make it more difficult ? Marc

On Wed, 15 Sep 2010 15:41:16 +0200, Marc Weustink wrote about Re: [Lazarus] Threads in Lazarus code base:

Show quoted text 9 lines
Graeme Geldenhuys wrote: > On 15 September 2010 13:25, Mattias Gaertner wrote:>> True. And I > have already plans to use some threads. Good to hear. > >> Threads have several disadvantages:> *They are harder to debug, > debugging with FPC+GDB is already hard, so there would be no > difference. ;-) So let's make it more difficult ?

I think Graeme's point is that FPC's linkage to GDB is made up largely of chewing gum and string as it is, so adding multi-threading does not make any significant increase in the difficulty.

FWIW, I have been doing multi-threading on mainframes since the 1970s. [It is called sub-tasking there.] I have never had any serious problems debugging concurrent sub-tasks, just as I do not have too many problems debugging multi-threaded code under Linux (today) or OS/2 (in the recent past).

This now brings us to the idea of building a debugger more suitable to FPC, Lazarus and the Pascal language generally.

Regards, Dave [RLU #314465] *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* (David W Noon) *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: not available URL: <http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100915/71bb377f/attachment.bin>

Reply by email

Mattias Gaertner
to Luiz Americo Pereira Camara: If i understand correctly all program will suffer the performance hit, not only the…
Show quoted text 7 lines
Mattias Gaertner escreveu: > *many IDE parts will become slower (once you start a thread the RTL > uses critical sections and especially string handling become much > slower). If i understand correctly all program will suffer the performance hit, not only the "threaded" part, right?

Correct. As long as another thread runs. When the thread stops all returns to "normal".

Do you have an idea of how slower string handling would be?

That heavily depends on the string operations you do. I saw two threads running slower than single threaded.

Show quoted text 5 lines
I'm asking this because i'm planning to make a client of a REST service through http and i choose Synapse to do the communication. Since Synapse recommends to use thread to avoid GUI freeze, i planned to use a thread for getting the data.

In this case you have not much choice.

Show quoted text 5 lines
At the other side this REST server uses JSON as the data format. If the thread really affects badly the string handling (and parsing JSON does a lot of it) i would rethink the strategy and go for an event based http client like lnet.

For performance relevant parts you should use PChar instead of strings. Even when doing single threaded.

I mentioned the speed difference because this thread is about using multi threading in the IDE and what advantages/disadvantages this might have.
The IDE is special in many ways, so don't take the comments of this thread as a general advice for your own programs.

Mattias

Reply by email

Luiz Americo Pereira Camara
to Mattias Gaertner
Mattias Gaertner wrote 18 lines
On Wed, 15 Sep 2010 11:49:42 -0300 Luiz Americo Pereira Camara wrote: > Mattias Gaertner escreveu: > >> *many IDE parts will become slower (once you start a thread the RTL >> uses critical sections and especially string handling become much >> slower). >> > If i understand correctly all program will suffer the performance hit, > not only the "threaded" part, right? > Correct. As long as another thread runs. When the thread stops all returns to "normal".

Thanks.
Good to know that when the thread stop the performance penalty "stops" This makes me keep with the original plan

[..]

Show quoted text 10 lines
> I'm asking this because i'm planning to make a client of a REST service > through http and i choose Synapse to do the communication. > > Since Synapse recommends to use thread to avoid GUI freeze, i planned to > use a thread for getting the data. > In this case you have not much choice.

I could use lnet.

But i think that this is not the case given the above

Luiz

Reply by email

Graeme Geldenhuys
to David W Noon: On Wed, 15 Sep 2010 15:41:16 +0200, Marc Weustink wrote about Re: [Lazarus] Threads in…

2010/9/15 David W Noon :

I think Graeme's point is that FPC's linkage to GDB is made up largely of chewing gum and string as it is, so adding multi-threading does not make any significant increase in the difficulty.

You understood me correctly.

This now brings us to the idea of building a debugger more suitable to FPC, Lazarus and the Pascal language generally.

The project Sven mentioned is Windows only. There is another project called 'duby' which is trying to achieve what you mention. I test it every now and again under 64-bit Linux. Duby is hosted on SourceForge.net. I also hope some day duby can replace the gdb requirement and have better support for Object Pascal language features.

svn co https://duby.svn.sourceforge.net/svnroot/duby

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Graeme Geldenhuys
to waldo kitty: the first think i'd probably end up doing is giving that sucker a much shorter name! :lol:
waldo kitty wrote
the first think i'd probably end up doing is giving that sucker a much shorter name! :lol:

:-) That name comes from being "delphi compatible". Good old Borland came up with that mouth full.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Michael Schnell
to Michael Schnell: That is why I vote for a message queue for the threads (implemented in the RTL). -Michael
Michael Schnell wrote
That is why I vote for a message queue for the threads (implemented in the RTL).

Just for the record:

I once tested (using Delphi) creating another TApplication instance in a TThread and without any problems I got a thread that not only does have it's own message queue but even a completely independent "Main Form".

Doing this in a decent platform independent way might require some work in the infrastructure, but I feel an improved way to handle this would be

- The RTL provides a system independent message queue implementation in native Pascal code (could easily be "stolen" from the LCL's KDE Widget Type code).

- for the main thread, the basic TApplication either uses this (KDE and most other Widget types) or replaces it by the OS'es message queue (Windows). Of course with this a decent "NoGUI" Widget Type is possible that implements a process-internal message queue without any GUI binding that allows for threads to notify the main thread, allows for TTimer and similar event sources to be handled in the normal "Delphi" way in a no-GUI application.

- For a TThread, the user can select (by a property of TThread or by different TThread-alike types) if he wants either of
- a traditional TThread "worker Thread" implementation without a message queue
- an "advanced worker thread" that has a message queue but no GUI binding (allowing to receive normal events form other threads and e.g. from TTimers)
- a thread that provides a TApplication instance and thus another independent "Main form"

Unfortunately while I suppose the software for this is not very hard to do (for someone knowledgeable with the Lazarus Widget Set implementations), to make this happen the Lazarus and FPC team would need to do a common synchronized update. I don't know if this is possible.

-.Michael

Reply by email

Juha Manninen gmail
to Juha Manninen gmail: Hi I thought first to send this to Lazarus dev list but it may have wider interest so I…

Ok, I used Application.AddOnIdleHandler for the task instead of a thread.

First I tried TIdleTimer first but it is confusing. Sometimes OnStartTimer handler was called first, sometimes OnTimer. What does Interval do when the context is idle time? What about AutoEnabled versus Enabled?

Now the form shows immediately but the controls on the form do not. It is all grey while the scan finction is running. Anyway, it is good enough, just not as good as the thread solution, and the implementation is clumsy.

I understood that FPC thread support is not perfect. That is the only valid reason not to use threads in this case. And why is a thread the best solution here?
Because there is no interaction between the tasks, except for the WaitFor in the end! Yes, there are such cases. OS kernel has an advanced system to give time slices to GUI thread when needed. It is stupid not to use this clever system.

A good general rule for any thread usage is:
As little interaction as possible!
If you need lots of interaction then don't use threads or change your design. For example a parallel loop is a perfect solution when the threads can run freely and finally the results are combined somehow.

I have (almost) only used "Synchronize" and "WaitFor" methods for thread interaction. Not because I was sloppy but because it was enough for my threads.

I honestly wonder the attitude against threads here. I hear comments of Pascal being a dying language from the past. Maybe it is true after all. How can one take seriously a developer community which claims threading is inherently wrong and bad?

BTW, TThread class has a good and intuitive interface, IMO. A new language syntax for parallelism would be nice but it wouldn't make any fundamental difference. Start a thread and call WaitFor later. How much easier can it be?

Juha

P.S.
I have the thread implementation of the cache function saved and waiting for better times.

Reply by email

Michael Van Canneyt
to Juha Manninen gmail
Juha Manninen wrote 5 lines
I honestly wonder the attitude against threads here. I hear comments of Pascal being a dying language from the past. Maybe it is true after all. How can one take seriously a developer community which claims threading is inherently wrong and bad?

The community doesn't claim so.
It is the result of independent research on the subject.

You must separate 'parallel computing' and 'threads'. Threads are one way of implementing parallel computing.

Note that the community doesn't say that parallel computing is bad; of course not; The opinion (of some, obviously) is simply that threads are not the best way of accomplishing parallel computing.

BTW, TThread class has a good and intuitive interface, IMO. A new language syntax for parallelism would be nice but it wouldn't make any fundamental difference. Start a thread and call WaitFor later. How much easier can it be?

No-one said that it was not easy to program threads. I use them myself extensively.

But the possible side effects were pointed out, and the consequences that usage of threads has IN THE IDE. And the opinion was raised that if there is a way to accomplishing the same task with our without using threads, then "no threads" is preferred for the IDE. This does not mean that a threading way will be rejected; you'll just need to argue the need for threads a bit more.

I understand that it may be harder and less easy for your particular task. Maybe you can submit your work so the IDE experts can offer better and more responsive ways of doing the task.

Michael.

Reply by email

Florian Klaempfl
to Juha Manninen gmail: Ok, I used Application.AddOnIdleHandler for the task instead of a thread. First I tried…
Juha Manninen (gmail) wrote
BTW, TThread class has a good and intuitive interface, IMO. A new language syntax for parallelism would be nice but it wouldn't make any fundamental difference. Start a thread and call WaitFor later. How much easier can it be?

Same can be said about goto and labels. Very intuitive and simple why bother about while, for, repeat loops?

Reply by email

Graeme Geldenhuys
to Michael Van Canneyt: The community doesn't claim so. It is the result of independent research on the subject.…
Michael Van Canneyt wrote
But the possible side effects were pointed out, and the consequences that usage of threads has IN THE IDE. And the opinion was raised that if there is a way to accomplishing the same task with our without using threads, then "no threads" is preferred for the IDE.

That's a bit unfair. Mattias already stated that he is planning some feature that will use multi-threading. So I really can't see why Juha can't implement his feature using multi-threading - especially if the implementation is simpler, produces better UI results and is simply more intuitive than idle timers and such.

MSEide, Delphi IDE, Visual Studio, MonoDevelop etc all use multiple threads in the IDE (it's common practice because the IDE is a perfect case for using threads - doing multiple tasks in the background while keeping the UI snappy). Why not Lazarus IDE?!? I really don't see what the fuss is about.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Graeme Geldenhuys
to Florian Klaempfl: Same can be said about goto and labels. Very intuitive and simple why bother about while,…
Florian Klaempfl wrote
Same can be said about goto and labels. Very intuitive and simple why bother about while, for, repeat loops?

Please keep such sarcasm to yourself, or as a private message to the individual. They don't contribute to the discussion and just bog up everybody's inboxes.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Michael Van Canneyt
to Graeme Geldenhuys: That's a bit unfair. Mattias already stated that he is planning some feature that will…
Graeme Geldenhuys wrote 11 lines
On 17 September 2010 10:43, Michael Van Canneyt wrote: > But the possible side effects were pointed out, and the consequences that > usage of threads has IN THE IDE. And the opinion was raised that if there is > a way to accomplishing the same task with our without using threads, then > "no threads" is preferred for the IDE. That's a bit unfair. Mattias already stated that he is planning some feature that will use multi-threading. So I really can't see why Juha can't implement his feature using multi-threading - especially if the implementation is simpler, produces better UI results and is simply more intuitive than idle timers and such.

Nobody said he cannot, but it would be setting a precedent with possibly heavy consequences.

Show quoted text 5 lines
MSEide, Delphi IDE, Visual Studio, MonoDevelop etc all use multiple threads in the IDE (it's common practice because the IDE is a perfect case for using threads - doing multiple tasks in the background while keeping the UI snappy). Why not Lazarus IDE?!? I really don't see what the fuss is about.

Well, the current implementation of the IDE is not thread safe.

And since the team has to do the maintenance of possible side-effects of threads, they are cautious. That's all there is to it.

Let's not make the issue bigger than it actually is.

Michael.

Reply by email

Florian Klaempfl
to Graeme Geldenhuys: Please keep such sarcasm to yourself, or as a private message to the individual. They…
Graeme Geldenhuys wrote 6 lines
On 17 September 2010 10:47, Florian Klaempfl wrote: > > Same can be said about goto and labels. Very intuitive and simple why > bother about while, for, repeat loops? Please keep such sarcasm

This is your personal opinion. I don't consider it as sarcasm but as truth. The current models of threading are imo simple flawed and need major improvements, maybe even a new programming paradigmas to be usable in programs in a robust and readable way.

to yourself, or as a private message to the individual.

Got list moderator?

They don't contribute to the discussion and just bog up everybody's inboxes.

Just use an filter.

Reply by email

Graeme Geldenhuys
to Florian Klaempfl
Florian Klaempfl wrote 5 lines
This is your personal opinion. I don't consider it as sarcasm but as truth. The current models of threading are imo simple flawed and need major improvements, maybe even a new programming paradigmas to be usable in programs in a robust and readable way.

Well, what are you waiting for? You created the Free Pascal Compiler, so create a new threading model. For the rest of us, we use what is available. TThread might not be perfect, but it is what we have, and has been working for tens of thousands of developers since Borland introduced it. Threading [like Pointers] are... "use with care, or stay away".

Juha's usage of multi-threading seems very clear and valid. The thread [and his implemented feature] is self-contained [not talking to other parts of the IDE], and the UI works is a safe manner with that specific thread. I see no issue with what he proposed.

Got list moderator?

Just following the rules that was made so clear to me. Off-topic (non-contributing to the discussion) messages belong in fpc-other or lazarus-other. Please respect the rules of the mailing list.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Juha Manninen gmail
to Michael Van Canneyt: The community doesn't claim so. It is the result of independent research on the subject.…
Michael Van Canneyt wrote
I understand that it may be harder and less easy for your particular task. Maybe you can submit your work so the IDE experts can offer better and more responsive ways of doing the task.

I committed it in r.27384.
Now I call AddOnIdleHandler before creating the form. I also tried passing variables through form constructor and calling AddOnIdleHandler from Form.OnCreate handler, like CodeBrowser does. It made no difference so I didn't commit it. I think CodeBrowser's secret is splitting the task and using a sequence state flag.

I think my solution is good enough now because the delay is typically short. Earlier there was no visual feedback, now there is a grey the IDE not being thread safe. Shouldn't it be defined for each function separately? A function can't be called from many threads so it is not thread safe. It must be decided case by case. "IDE" is too broad.

Juha

Reply by email

Florian Klaempfl
to Graeme Geldenhuys: Well, what are you waiting for? You created the Free Pascal Compiler, so create a new…
Graeme Geldenhuys wrote 8 lines
On 17 September 2010 11:11, Florian Klaempfl wrote: > > This is your personal opinion. I don't consider it as sarcasm but as > truth. The current models of threading are imo simple flawed and need > major improvements, maybe even a new programming paradigmas to be usable > in programs in a robust and readable way. Well, what are you waiting for?

For a good approach. I'am collecting and reading papers etc. about this topic for years. We need a quantum step in this regard as the structured programming was compared with spaghetti code.

Reply by email

Juha Manninen gmail
to Florian Klaempfl: Same can be said about goto and labels. Very intuitive and simple why bother about while,…
Florian Klaempfl wrote
Same can be said about goto and labels. Very intuitive and simple why bother about while, for, repeat loops?

Well, it is a valid comparison. I remember reading about new syntax in some languages. One is a "future variable" which you calculate in one place and then use later. Actually the compiler creates a thread for the calculation and does "waitfor" when the result is used first time. Cool!

Another was the "parallel" keyword for loops. Cool as well!

Then there was the closure / anonymous function in Delphi .NET. I forgot the details how it helps threading.

Anyway, I am happy if the new syntax is on a ToDo list for FPC. It will make things again easier and more intuitive. And it proves Pascal is in good shape for future computing challenges.

Juha

Reply by email

Vincent Snijders
to Graeme Geldenhuys: Please keep such sarcasm to yourself, or as a private message to the individual. They…

2010/9/17 Graeme Geldenhuys :

Show quoted text 9 lines
On 17 September 2010 10:47, Florian Klaempfl wrote: > > Same can be said about goto and labels. Very intuitive and simple why > bother about while, for, repeat loops? Please keep such sarcasm to yourself, or as a private message to the individual. They don't contribute to the discussion and just bog up everybody's inboxes.

Says the master of flame baits ....

Vincent

Reply by email

Vincent Snijders
to Juha Manninen gmail: I committed it in r.27384. Now I call AddOnIdleHandler before creating the form. I also…

2010/9/17 Juha Manninen (gmail) :

Show quoted text 6 lines
I committed it in r.27384. Now I call AddOnIdleHandler before creating the form. I also tried passing variables through form constructor and calling AddOnIdleHandler from Form.OnCreate handler, like CodeBrowser does. It made no difference so I didn't commit it. I think CodeBrowser's secret is splitting the task and using a sequence state flag.

Yes, I think so too.

I think my solution is good enough now because the delay is typically short. Earlier there was no visual feedback, now there is a grey form at least.

If you have only one step, I see no use for the OnIdle Handler, there are probably better events then, that fire when the form is shown or after it has been shown to the user.

Vincent

Reply by email

Michael Van Canneyt
to Juha Manninen gmail: I committed it in r.27384. Now I call AddOnIdleHandler before creating the form. I also…
Juha Manninen wrote 18 lines
On Friday 17 September 2010 11:43:24 Michael Van Canneyt wrote: > I understand that it may be harder and less easy for your particular task. > Maybe you can submit your work so the IDE experts can offer better and more > responsive ways of doing the task. I committed it in r.27384. Now I call AddOnIdleHandler before creating the form. I also tried passing variables through form constructor and calling AddOnIdleHandler from Form.OnCreate handler, like CodeBrowser does. It made no difference so I didn't commit it. I think CodeBrowser's secret is splitting the task and using a sequence state flag. I think my solution is good enough now because the delay is typically short. Earlier there was no visual feedback, now there is a grey form at least. About the IDE not being thread safe. Shouldn't it be defined for each function separately? A function can't be called from many threads so it is not thread safe. It must be decided case by case. "IDE" is too broad.

I agree.

But until this list of thread safe/not thread safe exists, it's better to be safe than sorry and assume nothing is thread safe :-)

Michael.

Reply by email

Michael Van Canneyt
to Michael Schnell: What other decent way is there to allow parallel computing (I here mean using multiple…
Michael Schnell wrote 5 lines
On 09/17/2010 10:43 AM, Michael Van Canneyt wrote: > Threads are one way of implementing parallel computing. What other decent way is there to allow parallel computing (I here mean using multiple CPUs) in a single program running on an SMP OS ?

Well, who says you need the 'single program' ?

In each case, it's a question for researchers.
I don't pretend to have answers.

But I do know from experience that thread synchronisation and communication is a problem when common data is used.

Michael.

Reply by email

Michael Schnell
to Juha Manninen gmail: Well, it is a valid comparison. I remember reading about new syntax in some languages.…
Juha Manninen wrote 11 lines
On Friday 17 September 2010 11:47:12 Florian Klaempfl wrote: > Same can be said about goto and labels. Very intuitive and simple why > bother about while, for, repeat loops? Well, it is a valid comparison. I remember reading about new syntax in some languages. One is a "future variable" which you calculate in one place and then use later. Actually the compiler creates a thread for the calculation and does "waitfor" when the result is used first time. Cool! Another was the "parallel" keyword for loops. Cool as well!

Since long I am raving about "Thread Events". (You might find some posts about this in the backlog of this list.)

Those are supposed to be procedural properties of objects. Currently those simply are called. When used as "Events", the Object calls them when appropriate and they are assigned to procedures by some code outside of the object. Thus they are used as "Callbacks".

This concept can be enhanced by assigning a thread to such an event with any call of same and execute the called procedure as this thread. Of course the function results and var parameters of such a beast would automatically be "futures"

This would make threads easy to create and use for the programmer, but of course it would not at all handle the potential complexity problems regarding mutual access, indeterminated code sequencing, and debugging.

-Michael

Reply by email

Florian Klaempfl
to Michael Schnell
Michael Schnell wrote 33 lines
On 09/17/2010 11:48 AM, Juha Manninen (gmail) wrote: > On Friday 17 September 2010 11:47:12 Florian Klaempfl wrote: >> Same can be said about goto and labels. Very intuitive and simple why >> bother about while, for, repeat loops? > Well, it is a valid comparison. I remember reading about new syntax in > some > languages. One is a "future variable" which you calculate in one place > and > then use later. Actually the compiler creates a thread for the > calculation and > does "waitfor" when the result is used first time. Cool! > > Another was the "parallel" keyword for loops. Cool as well! > > Since long I am raving about "Thread Events". (You might find some posts about this in the backlog of this list.) Those are supposed to be procedural properties of objects. Currently those simply are called. When used as "Events", the Object calls them when appropriate and they are assigned to procedures by some code outside of the object. Thus they are used as "Callbacks". This concept can be enhanced by assigning a thread to such an event with any call of same and execute the called procedure as this thread. Of course the function results and var parameters of such a beast would automatically be "futures" This would make threads easy to create and use for the programmer, but of course it would not at all handle the potential complexity problems regarding mutual access, indeterminated code sequencing, and debugging.

This is imo the real challenging part, besides mechanisms to abort threads. Especially because using the current mechanisms of synchronication, it is very hard to read multithreaded programs.

Reply by email

Dariusz Mazur
to Florian Klaempfl: The parallel loop solves nothing which makes threading hard and is only a cheap excuse.…
The parallel loop solves nothing which makes threading hard and is only a cheap excuse. The real problems of threading are synchronization and especially abording threads e.g. triggered by the main thread.

Whats about CILK http://en.wikipedia.org/wiki/Cilk

|_function_  fib (n: integer):integer;
var
   x,y : integer;
begin
      if (n<  2)  then exit(n)
      else begin
         x :=_spawn_  fib (n-1);
         y := fib (n-2);
         _sync_;
         exit(x+y);
     end;
end;
|
   Darek

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100917/fb4017c2/attachment.html>

Reply by email

Mattias Gärtner
to Vincent Snijders: 2010/9/17 Juha Manninen (gmail) : Yes, I think so too. If you have only one step, I see…

Zitat von Vincent Snijders :

Show quoted text 10 lines
2010/9/17 Juha Manninen (gmail) : > I committed it in r.27384. > Now I call AddOnIdleHandler before creating the form. I also tried passing > variables through form constructor and calling AddOnIdleHandler from > Form.OnCreate handler, like CodeBrowser does. It made no difference > so I didn't > commit it. I think CodeBrowser's secret is splitting the task and using a > sequence state flag. Yes, I think so too.

yes

Show quoted text 7 lines
> I think my solution is good enough now because the delay is typically short. > Earlier there was no visual feedback, now there is a grey form at least. > If you have only one step, I see no use for the OnIdle Handler, there are probably better events then, that fire when the form is shown or after it has been shown to the user.

Using any other event than OnIdle means, that some other events will be delayed for example paint events, which is exactly what Juha wants to avoid.

Mattias

Reply by email

Mattias Gaertner
to Dariusz Mazur: Whats about CILK http://en.wikipedia.org/wiki/Cilk |_function_ fib (n: integer):integer;…
Show quoted text 19 lines
[...] Whats about CILK http://en.wikipedia.org/wiki/Cilk |_function_ fib (n: integer):integer; var x,y : integer; begin if (n< 2) then exit(n) else begin x :=_spawn_ fib (n-1); y := fib (n-2); _sync_; exit(x+y); end; end; |

Have you noticed that most examples for multi threading are either
- easy to understand, but completely impractical (the above is an order of magnitude slower than single threaded)
- OR practical, but hard to understand
?

Note: afaik CILK is the same as parallel loops: It allows to make some special cases need less typing, can increase readability and can decrease overhead. As always with multithreading: wrongly used it can make code run much slower.

Mattias

Reply by email

Hans-Peter Diettrich
to Juha Manninen gmail: Well, it is a valid comparison. I remember reading about new syntax in some languages.…
Show quoted text 10 lines
On Friday 17 September 2010 11:47:12 Florian Klaempfl wrote: > Same can be said about goto and labels. Very intuitive and simple why > bother about while, for, repeat loops? Well, it is a valid comparison. I remember reading about new syntax in some languages. One is a "future variable" which you calculate in one place and then use later. Actually the compiler creates a thread for the calculation and does "waitfor" when the result is used first time. Cool! Another was the "parallel" keyword for loops. Cool as well!

We can consider all that candy when the basic (synchronization, debugging) problems have been solved. Realtime systems deserve the same mechanisms, and I don't remember any significantly new results from such research :-(

Anyway, I am happy if the new syntax is on a ToDo list for FPC. It will make things again easier and more intuitive. And it proves Pascal is in good shape for future computing challenges.

Every language can be extended with parallel execution features. Adding keywords is not the solution, in detail when the new features introduce more problems than they solve. Doing this now for FPC would only prove that FPC is a bunch of unfinished ideas, as some people say.

DoDi

Reply by email

Andrew Brunner
to Mattias Gaertner: On Fri, 17 Sep 2010 14:09:59 +0200 Have you noticed that most examples for multi…

I've been following this thread for a while and there has been much talk about the obvious trials but I have yet to read anything regarding the justification for the added overhead or the acceptance of parallelization (for perhaps some text searching)?

There is definitely great interest in making FPC Lazarus faster which I think will greatly enhance overall experience for developers.

Given the requirements and costs associated with complexities of managing Lazarus the modules associated with parallelization will need to be isolated as to not confuse any other group.

Merely adding the cthreads unit to Lazarus so we can have faster text searching seems like a trivial task. However, the developers tasked with integrating the improvements should really know the IDE inner workings as to AVOID blowing out the trunked version.

I personally have had problems getting trivial changes to Lazarus to propagate through the versions and would only offer an explanation that core developers are looking to get incomplete road map items and bugs resolved rather than accept code from people that are off on their own just excited about bringing their own technologies to the Lazarus community.

I have a feeling that all this discussion is for naught because even if you make the changes someone somewhere else will just simply not accept them. So, unless you SVN commit access and are interested in performing any low-level architectural changes to Lazarus - don't bother. And if you are serious the best way to get involved is to be tasked with an aspect of Lazarus development.

The time of dedicated Lazarus developers is extremely valuable and limited. It's nice to see ideas but Lazarus is a complicated system and it still has much further to go. It was only until recently did we get Multi-document feature ;-)

Getting the FPC team to embrace OLAPish technique to establish unit dependency hierarchy to parallelize FPC would be a better challenge and benefit to us all :-)

Reply by email

Dariusz Mazur
to Mattias Gaertner: On Fri, 17 Sep 2010 14:09:59 +0200 Have you noticed that most examples for multi…

W dniu 2010-09-17 17:49, Mattias Gaertner pisze:

Show quoted text 25 lines
On Fri, 17 Sep 2010 14:09:59 +0200 Dariusz Mazur wrote: > [...] > Whats about CILK http://en.wikipedia.org/wiki/Cilk > > > |_function_ fib (n: integer):integer; > var > x,y : integer; > begin > > if (n< 2) then exit(n) > else begin > > x :=_spawn_ fib (n-1); > y := fib (n-2); > _sync_; > exit(x+y); > end; > end; > | Have you noticed that most examples for multi threading are either - easy to understand, but completely impractical (the above is an order of magnitude slower than single threaded)

I don;t agee. First with CILK approach we deal with task, not threads. Thus we need good task passing to workers.
But seems, that this approach will be faster because on each SPAWN invoke we add only task (and this is very simple and short function, as add to FIFO queue)
And each worker (worker count is similar to cores) find task to do. Even when task are very different (shorter and longer) gueue pass task to worker with balancing . Why You think this will be magnitude slower I don't know.

- OR practical, but hard to understand ? Note: afaik CILK is the same as parallel loops:

No. On loop we divide iterations on start loops. When each iteration has different time of computing, we lost concurrence, because one thread finish, but rest work. Second: we not initialize thread on SPAWN (with loops threads are initializing on start loop), Workers wait for task on idle. Push and pop task from queue can be very fast. Of course this depend on implementation (for example each worker should deal with own queue, but should be possibility to draw task form other queue, this approach is faster than single MPMC FIFO queue)

It allows to make some special cases need less typing, can increase readability and can decrease overhead. As always with multithreading: wrongly used it can make code run much slower.

Multithreading is not only for faster computing.

Darek

Reply by email

Mattias Gaertner
to Dariusz Mazur
Show quoted text 35 lines
W dniu 2010-09-17 17:49, Mattias Gaertner pisze: > On Fri, 17 Sep 2010 14:09:59 +0200 > Dariusz Mazur wrote: > >> [...] >> Whats about CILK http://en.wikipedia.org/wiki/Cilk >> >> >> |_function_ fib (n: integer):integer; >> var >> x,y : integer; >> begin >> >> if (n< 2) then exit(n) >> else begin >> >> x :=_spawn_ fib (n-1); >> y := fib (n-2); >> _sync_; >> exit(x+y); >> end; >> end; >> | > Have you noticed that most examples for multi threading are either > - easy to understand, but completely impractical (the above is an > order of magnitude slower than single threaded) I don;t agee. First with CILK approach we deal with task, not threads. Thus we need good task passing to workers. But seems, that this approach will be faster because on each SPAWN invoke we add only task (and this is very simple and short function, as add to FIFO queue) And each worker (worker count is similar to cores) find task to do. Even when task are very different (shorter and longer) gueue pass task to worker with balancing . Why You think this will be magnitude slower I don't know.

Only the first 46 Fibonacci numbers fit into an integer, which a simple loop can compute. I don't know any task scheduler that produces less enough overhead to compute this faster.

Show quoted text 7 lines
> - OR practical, but hard to understand > ? > > Note: afaik CILK is the same as parallel loops: No. On loop we divide iterations on start loops. When each iteration has different time of computing, we lost concurrence, because one thread finish, but rest work.

And how does CILK solve this?

Show quoted text 6 lines
Second: we not initialize thread on SPAWN (with loops threads are initializing on start loop), Workers wait for task on idle. Push and pop task from queue can be very fast. Of course this depend on implementation (for example each worker should deal with own queue, but should be possibility to draw task form other queue, this approach is faster than single MPMC FIFO queue)

Ehm, you know that parallel loops normally use thread pools, do you?

Show quoted text 6 lines
> It allows to make some > special cases need less typing, can increase readability and can > decrease overhead. As always with multithreading: wrongly used it can > make code run much slower. Multithreading is not only for faster computing.

Does that mean, you agree?

Mattias

Reply by email

Marco van de Voort
to Michael Van Canneyt: Threads are a thing of the past as well. I've been programming threads since years. There…
Michael Van Canneyt wrote 6 lines
> I was amazed that there isn't a single use of threads in Lazarus code base. > Threads however are the thing of the future because computers have more and > more CPU cores. Threads are a way to utilize them. Threads are a thing of the past as well. I've been programming threads since years. There is nothing exciting about them, mostly they are a pain.

Well, one pain less. Delphi deprecated suspending/resuming of threads.

Reply by email

Andrew Brunner
to Marco van de Voort
Marco van de Voort wrote
Well, one pain less. Delphi deprecated suspending/resuming of threads.

That makes for interesting news. What about suspending / resuming Manager Systems that use threads for service applications... Sometimes you have to ask what where they thinking?

Reply by email

Sven Barth
to Marco van de Voort: Well, one pain less. Delphi deprecated suspending/resuming of threads.
Marco van de Voort wrote 10 lines
On Wed, Sep 15, 2010 at 10:48:09AM +0200, Michael Van Canneyt wrote: >> I was amazed that there isn't a single use of threads in Lazarus code base. >> Threads however are the thing of the future because computers have more and >> more CPU cores. Threads are a way to utilize them. > > Threads are a thing of the past as well. I've been programming threads since years. > There is nothing exciting about them, mostly they are a pain. Well, one pain less. Delphi deprecated suspending/resuming of threads.

Huh? O.o Did they give a reason for this move?

Regards,
Sven

Reply by email

Graeme Geldenhuys
to Sven Barth
Sven Barth wrote
> Well, one pain less. Delphi deprecated suspending/resuming of threads. Huh? O.o Did they give a reason for this move?

Quoting from a Linux website (but applies to windows and other platforms too)

"Notice that thr_suspend() is inherently dangerous and prone to race conditions. For one thing, there is no control on where the target thread stops: it can very well be stopped in the middle of a critical section, while holding mutexes. Also, there is no guarantee on when the target thread will actually stop. For these reasons, you'd be much better off using mutexes and conditions instead. The only situations that really require the ability to suspend a thread are debuggers and some kind of garbage collectors."

For a more detailed explanation (see why Java doesn't support it either):

http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Graeme Geldenhuys
to Andrew Brunner: That makes for interesting news. What about suspending / resuming Manager Systems that…
Andrew Brunner wrote
On Sat, Sep 18, 2010 at 5:17 PM, Marco van de Voort wrote: > Well, one pain less. Delphi deprecated suspending/resuming of threads. Sometimes you have to ask what where they thinking?

If you understand the possible problems, it is rather a question of: "Why did they take so long to deprecate the flaw". Imagine your thread has locked a major resource, now you suspend that thread. A instant deadlock occurs because that thread will never release that resource.

This Java website explains the problem rather well. http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Marco van de Voort
to Andrew Brunner: That makes for interesting news. What about suspending / resuming Manager Systems that…
Andrew Brunner wrote 5 lines
On Sat, Sep 18, 2010 at 5:17 PM, Marco van de Voort wrote: > Well, one pain less. Delphi deprecated suspending/resuming of threads. That makes for interesting news. What about suspending / resuming Manager Systems that use threads for service applications...

Just let them block on an tevent. On anything but windows (which has explicit support for suspending) that happens anyway. That is also one of the remedies they recommend btw.

Sometimes you have to ask what where they thinking?

They are preparing for multiplatform, and probably saw the mess the complications in the FPC rtl:-)

Reply by email

Sven Barth
to Graeme Geldenhuys: Quoting from a Linux website (but applies to windows and other platforms too) "Notice…
Graeme Geldenhuys wrote 22 lines
On 19 September 2010 11:12, Sven Barth wrote: >> Well, one pain less. Delphi deprecated suspending/resuming of threads. > > Huh? O.o Did they give a reason for this move? Quoting from a Linux website (but applies to windows and other platforms too) "Notice that thr_suspend() is inherently dangerous and prone to race conditions. For one thing, there is no control on where the target thread stops: it can very well be stopped in the middle of a critical section, while holding mutexes. Also, there is no guarantee on when the target thread will actually stop. For these reasons, you'd be much better off using mutexes and conditions instead. The only situations that really require the ability to suspend a thread are debuggers and some kind of garbage collectors." For a more detailed explanation (see why Java doesn't support it either): http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

Ok... that can be seen as a reason...

Regards,
Sven

Reply by email

Dariusz Mazur
to Mattias Gaertner: On Sat, 18 Sep 2010 18:08:09 +0200 Only the first 46 Fibonacci numbers fit into an…

W dniu 2010-09-18 18:55, Mattias Gaertner pisze:

Show quoted text 41 lines
On Sat, 18 Sep 2010 18:08:09 +0200 Dariusz Mazur wrote: > W dniu 2010-09-17 17:49, Mattias Gaertner pisze: >> On Fri, 17 Sep 2010 14:09:59 +0200 >> Dariusz Mazur wrote: >> >>> [...] >>> Whats about CILK http://en.wikipedia.org/wiki/Cilk >>> >>> >>> |_function_ fib (n: integer):integer; >>> var >>> x,y : integer; >>> begin >>> >>> if (n< 2) then exit(n) >>> else begin >>> >>> x :=_spawn_ fib (n-1); >>> y := fib (n-2); >>> _sync_; >>> exit(x+y); >>> end; >>> end; >>> | >> Have you noticed that most examples for multi threading are either >> - easy to understand, but completely impractical (the above is an >> order of magnitude slower than single threaded) > I don;t agee. First with CILK approach we deal with task, not threads. > Thus we need good task passing to workers. > But seems, that this approach will be faster because on each SPAWN > invoke we add only task (and this is very simple and short function, as > add to FIFO queue) > And each worker (worker count is similar to cores) find task to do. Even > when task are very different (shorter and longer) gueue pass task to > worker with balancing . Why You think this will be magnitude slower I > don't know. Only the first 46 Fibonacci numbers fit into an integer, which a simple loop can compute. I don't know any task scheduler that produces less enough overhead to compute this faster.

But this is not that case. Its can`t be compared do iteration computing. We can compare different algorithms. Faster than loop is cons array with results, but this tell nothing.
Its simple example to show, that CILK can play with recurrence (even with one invoke) . On real programs are many plays, that can be done concurrency, but when its to short, overhead in classic thread model is too big (computing or programing time).

Show quoted text 9 lines
>> - OR practical, but hard to understand >> ? >> >> Note: afaik CILK is the same as parallel loops: > No. On loop we divide iterations on start loops. When each iteration has > different time of computing, we lost concurrence, because one thread > finish, but rest work. And how does CILK solve this?

Pass task to workers. Each SPAWN start new task.
But good implementation of background is needed.

Its very similar to thread model, but not so heavy. Even short task can be computed efficiently

CILK has different attempt to task scheduling., its fullfil Work-requesting idea from
http://groups.google.com/group/lock-free/browse_frm/thread/18f90bdd8c721880

More on CILK documentation, I;m to weak in english.

Show quoted text 8 lines
> Second: we not initialize thread on SPAWN (with > loops threads are initializing on start loop), Workers wait for task on > idle. Push and pop task from queue can be very fast. Of course this > depend on implementation (for example each worker should deal with own > queue, but should be possibility to draw task form other queue, this > approach is faster than single MPMC FIFO queue) Ehm, you know that parallel loops normally use thread pools, do you?

Thats resolved only one problem.
Thread switching is done slowly (less than 100Hz) and rather expensive, thus we cant start one thread per iteration. We should a priori pass iteration to threads.

Show quoted text 7 lines
>> It allows to make some >> special cases need less typing, can increase readability and can >> decrease overhead. As always with multithreading: wrongly used it can >> make code run much slower. > Multithreading is not only for faster computing. Does that mean, you agree?

I don;t agree with statement: multithreading is hard thus we don`t use them

Darek -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://lists.lazarus.freepascal.org/pipermail/lazarus/attachments/20100919/66c07bcb/attachment.html>

Reply by email

Mattias Gaertner
to Dariusz Mazur
Show quoted text 28 lines
W dniu 2010-09-18 18:55, Mattias Gaertner pisze: [...] >>>> Whats about CILK http://en.wikipedia.org/wiki/Cilk >>>> >>>> >>>> |_function_ fib (n: integer):integer; >>>> var >>>> x,y : integer; >>>> begin >>>> >>>> if (n< 2) then exit(n) >>>> else begin >>>> >>>> x :=_spawn_ fib (n-1); >>>> y := fib (n-2); >>>> _sync_; >>>> exit(x+y); >>>> end; >>>> end; >>>> | [...] > Only the first 46 Fibonacci numbers fit into an integer, which a > simple loop can compute. I don't know any task scheduler > that produces less enough overhead to compute this faster. But this is not that case. Its can`t be compared do iteration computing. We can compare different algorithms. Faster than loop is cons array with results, but this tell nothing.

Yes, it does:
Before using multi threading, try to use a better single threaded algorithm. And when comparing multi with single threading speed, you must not compare a multi threaded algorithm running single threaded, but a multi threaded algorithm with a good single threaded algorithm.

Its simple example to show, that CILK can play with recurrence (even with one invoke).

Yes.
BTW: Same for parallel loops. You can write the above as parallel loop:

...
  for i:=0 to 1 paralleldo begin
    if i=0 then x := fib (n-1)
    else y := fib (n-2);
  end;
  exit(x+y);
...
Show quoted text 22 lines
On real programs are many plays, that can be done concurrency, but when its to short, overhead in classic thread model is too big (computing or programing time). >>> - OR practical, but hard to understand >>> ? >>> >>> Note: afaik CILK is the same as parallel loops: >> No. On loop we divide iterations on start loops. When each iteration has >> different time of computing, we lost concurrence, because one thread >> finish, but rest work. > And how does CILK solve this? Pass task to workers. Each SPAWN start new task. But good implementation of background is needed. Its very similar to thread model, but not so heavy. Even short task can be computed efficiently CILK has different attempt to task scheduling., its fullfil Work-requesting idea from http://groups.google.com/group/lock-free/browse_frm/thread/18f90bdd8c721880

That's an implementation detail. Parallel loops implementations can use this too. There are for example plugins for OpenMP using work stealing. Probably some use some form of work requesting too.

Show quoted text 14 lines
More on CILK documentation, I;m to weak in english. > >> Second: we not initialize thread on SPAWN (with >> loops threads are initializing on start loop), Workers wait for task on >> idle. Push and pop task from queue can be very fast. Of course this >> depend on implementation (for example each worker should deal with own >> queue, but should be possibility to draw task form other queue, this >> approach is faster than single MPMC FIFO queue) > Ehm, you know that parallel loops normally use thread pools, do you? Thats resolved only one problem. Thread switching is done slowly (less than 100Hz) and rather expensive, thus we cant start one thread per iteration. We should a priori pass iteration to threads.

Of course. I don't know any parallel loop implementation starting one thread per iteration (only in extreme cases).

Show quoted text 8 lines
>>> It allows to make some >>> special cases need less typing, can increase readability and can >>> decrease overhead. As always with multithreading: wrongly used it can >>> make code run much slower. >> Multithreading is not only for faster computing. > Does that mean, you agree? I don;t agree with statement: multithreading is hard thus we don`t use them

I didn't find a mail saying that, but I found a lot of: multithreading is hard thus we don`t use them without need.

Mattias

Reply by email

Dariusz Mazur
to Mattias Gaertner

W dniu 2010-09-20 09:25, Mattias Gaertner pisze:

Show quoted text 35 lines
On Sun, 19 Sep 2010 22:22:21 +0200 Dariusz Mazur wrote: > W dniu 2010-09-18 18:55, Mattias Gaertner pisze: > [...] >>>>> Whats about CILK http://en.wikipedia.org/wiki/Cilk >>>>> >>>>> >>>>> |_function_ fib (n: integer):integer; >>>>> var >>>>> x,y : integer; >>>>> begin >>>>> >>>>> if (n< 2) then exit(n) >>>>> else begin >>>>> >>>>> x :=_spawn_ fib (n-1); >>>>> y := fib (n-2); >>>>> _sync_; >>>>> exit(x+y); >>>>> end; >>>>> end; >>>>> | > [...] >> Only the first 46 Fibonacci numbers fit into an integer, which a >> simple loop can compute. I don't know any task scheduler >> that produces less enough overhead to compute this faster. > But this is not that case. Its can`t be compared do iteration computing. > We can compare different algorithms. Faster than loop is cons array with > results, but this tell nothing. Yes, it does: Before using multi threading, try to use a better single threaded algorithm. And when comparing multi with single threading speed, you must not compare a multi threaded algorithm running single threaded, but a multi threaded algorithm with a good single threaded algorithm.

I don;t talk about best solution of fibbonaci computing. But about possibility do deal with some class of task using multithreading. Its easy imagine task, which is hard to resolve with loops.

Show quoted text 14 lines
> Its simple example to show, that CILK can play with recurrence (even > with one invoke). Yes. BTW: Same for parallel loops. You can write the above as parallel loop: ... for i:=0 to 1 paralleldo begin if i=0 then x := fib (n-1) else y := fib (n-2); end; exit(x+y); ...

I doubt this run. Very soon you receive lack of threads. Second this two iteration has very different time of computing.
I don;t know approach, that balance this.
Third: readability is poor.

Show quoted text 22 lines
> On real programs are many plays, that can be done > concurrency, but when its to short, overhead in classic thread model is > too big (computing or programing time). > >>>> - OR practical, but hard to understand >>>> ? >>>> >>>> Note: afaik CILK is the same as parallel loops: >>> No. On loop we divide iterations on start loops. When each iteration has >>> different time of computing, we lost concurrence, because one thread >>> finish, but rest work. >> And how does CILK solve this? > Pass task to workers. Each SPAWN start new task. > But good implementation of background is needed. > > Its very similar to thread model, but not so heavy. Even short task can > be computed efficiently > > CILK has different attempt to task scheduling., its fullfil > Work-requesting idea from > http://groups.google.com/group/lock-free/browse_frm/thread/18f90bdd8c721880 That's an implementation detail.

This is not detail, but quite different attempt.

Parallel loops implementations can use this too. There are for example plugins for OpenMP using work stealing. Probably some use some form of work requesting too.

OpenMP is heavy framework, not suitable to all area. Some need something light. But as You notice, work stealing is not useless. Am best with strong integration with FPC.

Show quoted text 16 lines
> More on CILK documentation, I;m to weak in english. > >>> Second: we not initialize thread on SPAWN (with >>> loops threads are initializing on start loop), Workers wait for task on >>> idle. Push and pop task from queue can be very fast. Of course this >>> depend on implementation (for example each worker should deal with own >>> queue, but should be possibility to draw task form other queue, this >>> approach is faster than single MPMC FIFO queue) >> Ehm, you know that parallel loops normally use thread pools, do you? > Thats resolved only one problem. > Thread switching is done slowly (less than 100Hz) and rather expensive, > thus we cant start one thread per iteration. We should a priori pass > iteration to threads. Of course. I don't know any parallel loop implementation starting one thread per iteration (only in extreme cases).

But CILK can effective play with this.

Darek

Reply by email

Mattias Gärtner
to Dariusz Mazur

Zitat von Dariusz Mazur :

Show quoted text 8 lines
[...] > Before using multi threading, try to use a better single threaded > algorithm. And when comparing multi with single threading speed, you > must not compare a multi threaded algorithm running single threaded, but > a multi threaded algorithm with a good single threaded algorithm. I don;t talk about best solution of fibbonaci computing. But about possibility do deal with some class of task using multithreading. Its easy imagine task, which is hard to resolve with loops.

Of course.
I think, we both agree that CILK is a nice approach. I just said, that there are not many multi threading examples that are easy to read and are practical at the same time. Computing Fibonacci numbers does not need multi threading.

Show quoted text 16 lines
>> Its simple example to show, that CILK can play with recurrence (even >> with one invoke). > Yes. > BTW: Same for parallel loops. You can write the above as parallel loop: > > ... > for i:=0 to 1 paralleldo begin > if i=0 then x := fib (n-1) > else y := fib (n-2); > end; > exit(x+y); > ... > I doubt this run. Very soon you receive lack of threads. Second this two iteration has very different time of computing. I don;t know approach, that balance this.

Even the mtprocs does that.
http://wiki.lazarus.freepascal.org/Parallel_procedures#Features

Of course mtprocs has some disadvantages, e.g. it uses slow critical sections and task size must be tuned by the programmer.

Third: readability is poor.

Compare this to OpenMP programs. ;)

Show quoted text 13 lines
[...] >> CILK has different attempt to task scheduling., its fullfil >> Work-requesting idea from >> http://groups.google.com/group/lock-free/browse_frm/thread/18f90bdd8c721880 > That's an implementation detail. This is not detail, but quite different attempt. > Parallel loops implementations can use > this too. There are for example plugins for OpenMP using work stealing. > Probably some use some form of work requesting too. OpenMP is heavy framework, not suitable to all area. Some need something light. But as You notice, work stealing is not useless. Am best with strong integration with FPC.

Yes, that would be nice.

Show quoted text 16 lines
>> More on CILK documentation, I;m to weak in english. >> >>>> Second: we not initialize thread on SPAWN (with >>>> loops threads are initializing on start loop), Workers wait for task on >>>> idle. Push and pop task from queue can be very fast. Of course this >>>> depend on implementation (for example each worker should deal with own >>>> queue, but should be possibility to draw task form other queue, this >>>> approach is faster than single MPMC FIFO queue) >>> Ehm, you know that parallel loops normally use thread pools, do you? >> Thats resolved only one problem. >> Thread switching is done slowly (less than 100Hz) and rather expensive, >> thus we cant start one thread per iteration. We should a priori pass >> iteration to threads. > Of course. I don't know any parallel loop implementation starting one > thread per iteration (only in extreme cases). But CILK can effective play with this.

I doubt that. For example:

for i:=1 to 100000000 do
   spawn DoSomething(i);

It will work (unless run out of mem), but it obviously needs some tuning.

Mattias

Reply by email

Dariusz Mazur
to Mattias Gärtner

W dniu 2010-09-20 13:55, Mattias G?rtner pisze:

Show quoted text 14 lines
Zitat von Dariusz Mazur : > [...] >> Before using multi threading, try to use a better single threaded >> algorithm. And when comparing multi with single threading speed, you >> must not compare a multi threaded algorithm running single threaded, >> but >> a multi threaded algorithm with a good single threaded algorithm. > I don;t talk about best solution of fibbonaci computing. But about > possibility do deal with some class of task using multithreading. > Its easy imagine task, which is hard to resolve with loops. Of course. I think, we both agree that CILK is a nice approach.

Nice to hear this.

I just said, that there are not many multi threading examples that are easy to read and are practical at the same time. Computing Fibonacci numbers does not need multi threading.

Most of programs are huge count of simple computing. There are many places, that things may run parallel without pain. But very often this places are computing short, thus very often overhead of starting thread is bigger than using second core. But CILK potentially (I can prof that, only imagine) reduce this overhead. Second : its very readability solution, and compiler potentially can warning about some danger . If we try to concurrency smaller things, without loss efficiency, danger will be minimize

Show quoted text 20 lines
>>> Its simple example to show, that CILK can play with recurrence (even >>> with one invoke). >> Yes. >> BTW: Same for parallel loops. You can write the above as parallel loop: >> >> ... >> for i:=0 to 1 paralleldo begin >> if i=0 then x := fib (n-1) >> else y := fib (n-2); >> end; >> exit(x+y); >> ... >> > I doubt this run. Very soon you receive lack of threads. Second this > two iteration has very different time of computing. > I don;t know approach, that balance this. Even the mtprocs does that. http://wiki.lazarus.freepascal.org/Parallel_procedures#Features

realy?
cite:" a procedure or method is executed with an Index running from an arbitrary StartIndex to an arbitrary EndIndex"

assigning iteration to threads are done on start loop, eq. we must know count of iteration.
what when iteration 1 is ten times longer than rest?

Show quoted text 26 lines
Of course mtprocs has some disadvantages, e.g. it uses slow critical sections and task size must be tuned by the programmer. > Third: readability is poor. Compare this to OpenMP programs. ;) > [...] >>> CILK has different attempt to task scheduling., its fullfil >>> Work-requesting idea from >>> http://groups.google.com/group/lock-free/browse_frm/thread/18f90bdd8c721880 >>> >> That's an implementation detail. > This is not detail, but quite different attempt. > >> Parallel loops implementations can use >> this too. There are for example plugins for OpenMP using work stealing. >> Probably some use some form of work requesting too. > OpenMP is heavy framework, not suitable to all area. Some need > something light. But as You notice, work stealing is not useless. Am > best with strong integration with FPC. Yes, that would be nice.

But some one should choose on approach, even weak, and start play with them. Till now every one (me too) complaint: my solution is better.

Show quoted text 28 lines
>>> More on CILK documentation, I;m to weak in english. >>> >>>>> Second: we not initialize thread on SPAWN (with >>>>> loops threads are initializing on start loop), Workers wait for >>>>> task on >>>>> idle. Push and pop task from queue can be very fast. Of course this >>>>> depend on implementation (for example each worker should deal >>>>> with own >>>>> queue, but should be possibility to draw task form other queue, this >>>>> approach is faster than single MPMC FIFO queue) >>>> Ehm, you know that parallel loops normally use thread pools, do you? >>> Thats resolved only one problem. >>> Thread switching is done slowly (less than 100Hz) and rather >>> expensive, >>> thus we cant start one thread per iteration. We should a priori pass >>> iteration to threads. >> Of course. I don't know any parallel loop implementation starting one >> thread per iteration (only in extreme cases). > But CILK can effective play with this. I doubt that. For example: for i:=1 to 100000000 do spawn DoSomething(i); It will work (unless run out of mem), but it obviously needs some tuning.
but
for i:=1 to 1000000 do
   spawn DoSomething(i);

should work,

I thinking about Fifo queue, I use one Lock free,
its need 16 byte per spawn (func addres, param and result) time of swich less than 1us

problem is with assigning local stack per task, my asm is too weak.

Darek

Reply by email

Mattias Gärtner
to Dariusz Mazur

Zitat von Dariusz Mazur :

Show quoted text 9 lines
[...] Most of programs are huge count of simple computing. There are many places, that things may run parallel without pain. But very often this places are computing short, thus very often overhead of starting thread is bigger than using second core. But CILK potentially (I can prof that, only imagine) reduce this overhead. Second : its very readability solution, and compiler potentially can warning about some danger . If we try to concurrency smaller things, without loss efficiency, danger will be minimize

Start a wiki page with a proposal for the syntax.
Create a unit like mtprocs that demonstrates CILK and how the syntax should be converted by the compiler.
Find someone to implement and, more important, maintain this. Then there is a good chance to get this into the fpc main branch.

Show quoted text 10 lines
[...] > Even the mtprocs does that. > http://wiki.lazarus.freepascal.org/Parallel_procedures#Features realy? cite:" a procedure or method is executed with an Index running from an arbitrary StartIndex to an arbitrary EndIndex" assigning iteration to threads are done on start loop, eq. we must know count of iteration. what when iteration 1 is ten times longer than rest?

Then the other threads will sleep OR if this is a nested sub procedure the other threads will continue on the other work. For example:

for i:=1 to 10 paralleldo
   for j:=1 to 10 paralleldo begin
     if j=1 then DoAlotOfWork else DoLittleWork;
   end;

With mtprocs all threads will work until the end when the everything was done except the last DoAlotOfWork, which is then executed by only one thread.

mtprocs is just a unit, it can not auto parallelize DoAlotOfWork as a compiler could.

[...] I thinking about Fifo queue, I use one Lock free, its need 16 byte per spawn (func addres, param and result) time of swich less than 1us

Are you sure about the 1us switch? The algorithm looks more dramatic.

problem is with assigning local stack per task, my asm is too weak.

Mattias

Reply by email

Sven Barth
to Dariusz Mazur: W dniu 2010-09-20 13:55, Mattias G?rtner pisze: Nice to hear this. Most of programs are…
Dariusz Mazur wrote 24 lines
W dniu 2010-09-20 13:55, Mattias G?rtner pisze: > Zitat von Dariusz Mazur : > >> [...] >>> Before using multi threading, try to use a better single threaded >>> algorithm. And when comparing multi with single threading speed, you >>> must not compare a multi threaded algorithm running single threaded, >>> but >>> a multi threaded algorithm with a good single threaded algorithm. >> I don;t talk about best solution of fibbonaci computing. But about >> possibility do deal with some class of task using multithreading. >> Its easy imagine task, which is hard to resolve with loops. > > Of course. > I think, we both agree that CILK is a nice approach. Nice to hear this. > I just said, that there are not many multi threading examples that are > easy to read and are practical at the same time. Computing Fibonacci > numbers does not need multi threading. > Most of programs are huge count of simple computing. There are many places, that things may run parallel without pain. But very often this places are computing short, thus very often overhead of starting thread is bigger than using second core.

You are aware that for using a second core you need a thread (no matter how fancy a syntax construct hides it)? Thus for reducing the overhead of creating a thread at least one thread per core must be created before the first call of a "spawned" function/procedure.

Regards,
Sven

Reply by email

Felipe Monteiro de Carvalho
to Sven Barth

I like the current TThread =)

I am writing a strategy game and I noticed how much time it takes to load the map, so why make the user wait? I simply put the map loading in a thread and while the map loads the user can use the user interface to choose a scenario or configure the game. If he is faster then the map loading then he will have to wait at the end. If he is slower, then he will have no waiting =)

Worked excellently in both Windows and Mac OS X.

I agree that it should be avoided most of the times, but in some special cases it can be the best solution.

In the particular case maybe seeing a patch would clarify things. Then one can discuss in more detail if it is positive or if another solution is better. The discussion got too theoretical (not to mention a couple of flames).

Felipe Monteiro de Carvalho

Reply by email

Dariusz Mazur
to Sven Barth: You are aware that for using a second core you need a thread (no matter how fancy a…

W dniu 2010-09-20 16:09, Sven Barth pisze:

Show quoted text 30 lines
Am 20.09.2010 15:22, schrieb Dariusz Mazur: > W dniu 2010-09-20 13:55, Mattias G?rtner pisze: >> Zitat von Dariusz Mazur : >> >>> [...] >>>> Before using multi threading, try to use a better single threaded >>>> algorithm. And when comparing multi with single threading speed, you >>>> must not compare a multi threaded algorithm running single threaded, >>>> but >>>> a multi threaded algorithm with a good single threaded algorithm. >>> I don;t talk about best solution of fibbonaci computing. But about >>> possibility do deal with some class of task using multithreading. >>> Its easy imagine task, which is hard to resolve with loops. >> >> Of course. >> I think, we both agree that CILK is a nice approach. > Nice to hear this. >> I just said, that there are not many multi threading examples that are >> easy to read and are practical at the same time. Computing Fibonacci >> numbers does not need multi threading. >> > Most of programs are huge count of simple computing. There are many > places, that things may run parallel without pain. But very often this > places are computing short, thus very often overhead of starting thread > is bigger than using second core. You are aware that for using a second core you need a thread (no matter how fancy a syntax construct hides it)? Thus for reducing the overhead of creating a thread at least one thread per core must be created before the first call of a "spawned" function/procedure.

Of course, Some of workers (threads) sleep, Also queue must be initializing. But i think its not a problem.

Darek

Reply by email

Dariusz Mazur
to Mattias Gärtner: Zitat von Dariusz Mazur : Start a wiki page with a proposal for the syntax. Create a unit…

W dniu 2010-09-20 16:03, Mattias G?rtner pisze:

Show quoted text 17 lines
Zitat von Dariusz Mazur : > [...] > Most of programs are huge count of simple computing. There are many > places, that things may run parallel without pain. But very often > this places are computing short, thus very often overhead of starting > thread is bigger than using second core. But CILK potentially (I can > prof that, only imagine) reduce this overhead. Second : its very > readability solution, and compiler potentially can warning about some > danger . If we try to concurrency smaller things, without loss > efficiency, danger will be minimize Start a wiki page with a proposal for the syntax. Create a unit like mtprocs that demonstrates CILK and how the syntax should be converted by the compiler. Find someone to implement and, more important, maintain this. Then there is a good chance to get this into the fpc main branch.

I know, every one say this. But without help (or even permission) of core developer its none chance to achieve this. I can prepare some of units, but because i;m rather poor with documentation its little chance to achieve this.

Show quoted text 28 lines
> [...] >> Even the mtprocs does that. >> http://wiki.lazarus.freepascal.org/Parallel_procedures#Features > realy? > cite:" a procedure or method is executed with an Index running from > an arbitrary StartIndex to an arbitrary EndIndex" > > assigning iteration to threads are done on start loop, eq. we must > know count of iteration. > what when iteration 1 is ten times longer than rest? Then the other threads will sleep OR if this is a nested sub procedure the other threads will continue on the other work. For example: for i:=1 to 10 paralleldo for j:=1 to 10 paralleldo begin if j=1 then DoAlotOfWork else DoLittleWork; end; With mtprocs all threads will work until the end when the everything was done except the last DoAlotOfWork, which is then executed by only one thread. mtprocs is just a unit, it can not auto parallelize DoAlotOfWork as a compiler could.

No, its just by architecture. Iterations are divide between threads. Because thread are limited and costly we must limit granularity. CILK may work the same, also with loops, but main difference is under.

Show quoted text 8 lines
> [...] > I thinking about Fifo queue, I use one Lock free, > its need 16 byte per spawn (func addres, param and result) > time of swich less than 1us Are you sure about the 1us switch? The algorithm looks more dramatic.

Which algorithm? I say about pop and push form lock free queue. I use this heavy with my webserver to distributing messages.

Darek

Reply by email

Mattias Gaertner
to Dariusz Mazur
Show quoted text 10 lines
[...] > Start a wiki page with a proposal for the syntax. > Create a unit like mtprocs that demonstrates CILK and how the syntax > should be converted by the compiler. > Find someone to implement and, more important, maintain this. > Then there is a good chance to get this into the fpc main branch. I know, every one say this. But without help (or even permission) of core developer its none chance to achieve this. I can prepare some of units, but because i;m rather poor with documentation its little chance to achieve this.

You will get permission when you convince them that someone will maintain it for the next years.
First do the wiki and a unit to test.

Show quoted text 15 lines
>> [...] > for i:=1 to 10 paralleldo > for j:=1 to 10 paralleldo begin > if j=1 then DoAlotOfWork else DoLittleWork; > end; > > With mtprocs all threads will work until the end when the everything > was done except the last DoAlotOfWork, which is then executed by only > one thread. > > mtprocs is just a unit, it can not auto parallelize DoAlotOfWork as a > compiler could. No, its just by architecture. Iterations are divide between threads. Because thread are limited and costly we must limit granularity. CILK may work the same, also with loops, but main difference is under.

I don't understand what you want to say here, but I guess the answers will lead too far away from lazarus anyway. I will wait for your implementation.

Show quoted text 9 lines
>> [...] >> I thinking about Fifo queue, I use one Lock free, >> its need 16 byte per spawn (func addres, param and result) >> time of swich less than 1us > > Are you sure about the 1us switch? The algorithm looks more dramatic. Which algorithm? I say about pop and push form lock free queue. I use this heavy with my webserver to distributing messages.

Sorry, I thought you was talking about the CILK scheduler.

Mattias

Reply by email

Michael Schnell
to Mattias Gaertner: On Fri, 17 Sep 2010 14:09:59 +0200 Have you noticed that most examples for multi…
Mattias Gaertner wrote
Note: afaik CILK is the same as parallel loops: It allows to make some special cases need less typing, can increase readability and can decrease overhead.

Of course "parallel loops" is "just less typing" than doing the same functionality in user code.

Same is true for the complete RTL.

In fact parallel loops ask for an automatically managed thread pool. This of course should be provided by a library. The "parallel"!, "future" and related keywords for enhancing the syntax would of course be "compiler candy" top make it more usable.

-Michael

Reply by email

Michael Schnell
to Dariusz Mazur: W dniu 2010-09-17 17:49, Mattias Gaertner pisze: I don;t agee. First with CILK approach…
Dariusz Mazur wrote
with CILK approach we deal with task, not threads.

IMHO this does not make much sense.

For the user-programmer, the relevant difference between tasks and threads is that thread share memory.

This results in the increasing complexity with mutually accessed variables which of course provides a real challenge.

But you can think of a programming paradigm (=CILK") that does not allow the user programmer to share the variables between the "tasks" even though the "tasks" in fact are threads as far as the OS is concerned.

Not the tasks switch is done with a lot less overhead as the OS does not need to change the environment (such as MMU tables), the cache is used more efficiently (especially on ARM as here the cache needs to be cleared with each change in the MMU tables).

The communication between the tasks (here done not by the user but by would be automated the system (e.g. CILK) would be a lot faster when it uses threads instead of processes, as it could easily make uses of shared memory (though hidden from the user).

Moreover, while debugging multiple threads is more difficult than debugging single threaded applications, parallel debugging of multiple applications is still more heavy.

-Michael

Reply by email

Michael Schnell
to Mattias Gärtner: Zitat von Dariusz Mazur : Of course. I think, we both agree that CILK is a nice approach.…
Mattias G?rtner wrote 5 lines
for i:=1 to 100000000 do spawn DoSomething(i);

Who has a 100000000 Core hardware ?

But with some Super-Computers, spawning some thousand DoSomethings might be viable.

Usually any type of "parallel" implementation in a language or a library would limit the count of spawned tasks to a number lower than the count of CPUs available.

-Michael

Reply by email

Michael Schnell
to Graeme Geldenhuys: If you understand the possible problems, it is rather a question of: "Why did they take…
Graeme Geldenhuys wrote 7 lines
If you understand the possible problems, it is rather a question of: "Why did they take so long to deprecate the flaw". Imagine your thread has locked a major resource, now you suspend that thread. A instant deadlock occurs because that thread will never release that resource.

I used threads very often and I never used "suspend" and friends for synchronizing. I do use critical sectrions, events and messages. IMHO this makes a lot more sense.

-Michael

Reply by email

Michael Fuchs
to Michael Schnell: Who has a 100000000 Core hardware ? But with some Super-Computers, spawning some thousand…
Michael Schnell wrote
Usually any type of "parallel" implementation in a language or a library would limit the count of spawned tasks to a number lower than the count of CPUs available.

You mean n-1 parallel tasks for n CPUs? That will be very bad on a single core machine. ;)

And if I remember the usage of MAKEOPTS in make.conf is the right setting for parallel compiling tasks (CountOfCpu + 1).

Michael

Reply by email

Michael Schnell
to Michael Fuchs
Michael Fuchs wrote 7 lines
Am 21.09.2010 09:59, schrieb Michael Schnell: > Usually any type of "parallel" implementation in a language or a library > would limit the count of spawned tasks to a number lower than the count > of CPUs available. You mean n-1 parallel tasks for n CPUs? That will be very bad on a single core machine. ;)

Not at all :)

n-1 additional parallel tasks will be spawned. The tasks to do will dynamically be assigned to those and be assigned another one it one is done. I suppose if appropriate (i.e. if it needs to wait for result due to a "future variable" or a similar restriction, the main thread will be assigned the tasks as well.

The nice thing about syntax concepts such as "parallel" and "future" is that the user does not _need_ to deal with the multi-threading complexity, even though it does not prevent the user from committing huge mistakes when he in fact does (e.g. by writing to variables commonly used by multiple parallel loop runs, which can be done implicitly and thus hard to detect).

-Michael

Reply by email

Graeme Geldenhuys
to Michael Schnell: I used threads very often and I never used "suspend" and friends for synchronizing. I do…
Michael Schnell wrote 7 lines
> ... > thread has locked a major resource, now you suspend that thread. A > instant deadlock occurs because that thread will never release that > resource. > I used threads very often and I never used "suspend" and friends for synchronizing.

I never suspend threads either, but I did play with that function (and all other functions associated with TThread) while I created a Thread Manager Demo application. The demo was part of my work, by evaluating FPC's TThread support on various platforms and to see if functionality behave the same.

Initially that demo did reveal some nasties under Linux, and clearly showed the difference between the thread schedulers of Linux and Windows. If memory serves me well, suspending a thread caused the whole X11 desktop UI to freeze, but I believe this behaviour was changed in FPC.

Regards, ? - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/

Reply by email

Dariusz Mazur
to Michael Schnell: IMHO this does not make much sense. For the user-programmer, the relevant difference…

W dniu 2010-09-21 09:51, Michael Schnell pisze:

Show quoted text 24 lines
On 09/18/2010 06:08 PM, Dariusz Mazur wrote: > with CILK approach we deal with task, not threads. IMHO this does not make much sense. For the user-programmer, the relevant difference between tasks and threads is that thread share memory. This results in the increasing complexity with mutually accessed variables which of course provides a real challenge. But you can think of a programming paradigm (=CILK") that does not allow the user programmer to share the variables between the "tasks" even though the "tasks" in fact are threads as far as the OS is concerned. Not the tasks switch is done with a lot less overhead as the OS does not need to change the environment (such as MMU tables), the cache is used more efficiently (especially on ARM as here the cache needs to be cleared with each change in the MMU tables). The communication between the tasks (here done not by the user but by would be automated the system (e.g. CILK) would be a lot faster when it uses threads instead of processes, as it could easily make uses of shared memory (though hidden from the user).

I don;t understand. You say "processes" , but i don't talk about it. Task for me (in CILK approach) is thing, that only program itself care about without OS help (as in threads).
Task is function, which can be invoke by worker any time (similar to events) and stop on sync. Deal with memory is the same as normal MT program. Workers run as normal threads.

Darek

Reply by email