Click here to Skip to main content
15,881,812 members
Everything / Multi-threading

Multi-threading

multi-threading

Great Reads

by Eric Ouellet, Sani Huttunen
Fast implementations of permutation algorithms
by Piotr Grygorczuk
Enable C++11 multithreading features in GCC for FreeRTOS
by Petrov Vladimir
Starting Threads in MFC and Win32 and some handling samples
by ObiWan_MCC
A C# SMTP server (receiver).

Latest Articles

by Piotr Grygorczuk
Enable C++11 multithreading features in GCC for FreeRTOS
by Oleg_100
Synchronize access to multiple objects by name (string)
by ls6777
Task monitor for multi-threaded embedded systems
by Eric Ouellet, Sani Huttunen
Fast implementations of permutation algorithms

All Articles

Sort by Score

Multi-threading 

11 Oct 2022 by Eric Ouellet, Sani Huttunen
Fast implementations of permutation algorithms
30 Mar 2023 by Piotr Grygorczuk
Enable C++11 multithreading features in GCC for FreeRTOS
17 Oct 2021 by Petrov Vladimir
Starting Threads in MFC and Win32 and some handling samples
13 Aug 2013 by Florian Rappl
Creating a highly extensible presentation app with multi-user and device integration for tablets.
11 Sep 2022 by Mark Pelf
Tutorial article on Observer pattern in C#
18 Mar 2016 by Richard Deeming
Task.Delay will create a new Task (technically, a DelayPromise) and a Timer:Task.Delay | Reference Source[^]However, in your example, it will do this once per second. It won't "whiz round" creating new objects in a tight loop, because the await ensures that the rest of the method doesn't...
15 Jul 2011 by Sergey Alexandrovich Kryukov
The simplest way: create a CriticalSection (is it Windows?) and write a separate output function, sandwich its body with EnterCriticalSection and LeaveCriticalSection; output to console only through this function.Next time: please always indicate your platform in your question. Other detail...
9 Mar 2011 by Manfred Rudolf Bihy
If it were OK for you to use PowerShell multithreading would indeed be an option. I found an example here: http://blog.isaacblum.com/2010/01/22/powershell-multithreading-omg/[^]. Googling +PowerShell +Multithreading yields 111K results. I'm sure you'll find more examples as you come...
11 Mar 2011 by Sergey Alexandrovich Kryukov
Both criteria are nonsense. There are many reasons to use threading, but only for some tasks 100% of CPU usage is desired. Example of such task is long-lasting calculations without human intervention. There are many such tasks, such as numerical simulation of complex models. But! In all these...
17 May 2011 by tolw
1. The 'generally unclear part' is the constructor initialization list. And it does what the name suggests. It initializes class fields before anything else from the body of the constructor is called. Have a look at google for more info. One of the links: Click[^]2. :: before a method name...
29 Feb 2012 by Dave Kreskowiak
This isn't described very well.But, you're saying that all three methods are executing at the same time?? Congratulations! You wrote your code to launch three different BackgroundWorkers or spawned your own threads to do it!All you would have to do is create ONE BackgroundWorker and...
8 Apr 2012 by Vladislav Socolov
Hi! Try to read this article: "Threading in C#" from Joseph Albahari. It was very useful for me to understand basics concepts of multithreading in c#.
15 Jun 2012 by enhzflep
Gday, I'm not so sure I understand each of your points and your questions - though I'll do what I can to address them.XBox, PS3 actually only have a couple of cores, like PCs. PS3 - 8 for the cell, 6 as implemented in ps3 variants.Xbox360 - 3 for the PowerPC XenonJust like PCs, the...
1 Apr 2016 by Dave Kreskowiak
This problem cannot be solved by threading. Without using locking, you cannot guarantee the order in which threads run. You CAN get a thread order like 1, 2, 3, 1, 3, 2, 3, 1, 2, 1, ...Introducing locking to get the correct order just makes these threads execute synchronously, no different...
27 Feb 2021 by honey the codewitch
Using a popular RTOS to enable easy multithreading on your IoT gadgets
12 Nov 2022 by ls6777
Task monitor for multi-threaded embedded systems
8 Feb 2011 by Sergey Alexandrovich Kryukov
I cannot give you the explanation of the threading concept in any comprehensive method because: 1) it will require to write a whole book; 2) you did not provide any code to illustrate your needs, so it's hard to limit my advice by the threading aspects which would fit your application. You gave...
8 Feb 2011 by #realJSOP
DO NOT USE TIMER OBJECTS (I say this over, and over, and over again). On a busy system, the timer messages are NOT guaranteed to be sent. Use real threads instead. In fact, you might even want to consider using a thread pool so that only a limited number of threads can be executed at any...
9 Mar 2011 by #realJSOP
Start multiple instances of the same console app. Each running application under Windows exists within its own thread.Beyond that, you shouldn't have to mess with assigning core affinity because .Net apps combined with Windows 7 will make the most efficient use of your system's architecture...
9 May 2011 by Laurence1234
Hi everyone, I've written an application in C# that uses WPF (utilising the MVVM design pattern) and LINQ to CRM to retrieve data from a database. I have a problem with threading it seems...This application uses the BackgroundWorker to run a database query. Once it retrieves this...
17 May 2011 by Olivier Levrey
tolw's answer is good. I will just add a note about question 2: the ::AfxBeginThread syntax.In this case the code will compile with or without the ::. The code writer just wanted to focus on the fact that this function is not part of his class but is part of the global scope as tolw already...
20 Sep 2011 by Prerak Patel
What you are doing is not multithreading. Check out the links to learn more about ithttp://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx[^]Multithreading in .NET[^]Multithreading Concepts in C#[^]
23 Sep 2011 by E.F. Nijboer
This is a classic producer/consumer problem that needs synchronization to make it work properly. It's just like in real life, it is impossible to write both at the same time using just one pencil. You need to make rules about sharing or make one person responsible for writing stuff...
15 Jun 2012 by Stephen Hewison
More cores quite simply means you can do more at any one time. Most cores also support threading. Processors work using something called the fetch execute cycle. This cycle has 4 stages and it's possible for 4 separate threads to work within a single processor as each one exists within each...
20 Jun 2012 by ThatsAlok
CWinThread with TWO-Way communication using window message
17 Feb 2013 by Sergey Alexandrovich Kryukov
It really depends on your UI library and what you call rendering. In WPF, for example, rendering is already a thread separate from UI thread. I don't think this is a correctly posed question. In all cases, you should separate the game scenario from UI. Then you just have to render the scene in...
15 Oct 2013 by User 59241
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.From msdn:TerminateThread...
6 Nov 2013 by Bill_Hallahan
You can have the launched thread routine contain code that causes the thread routine to return. This will automatically cause ExitThread to be called. Your code can wait on the thread handle using the WaitForSingleObject function and when EndThread is called, WaitForSingleObject will unblock. ...
15 Feb 2014 by Sergey Alexandrovich Kryukov
Here is the bug:for (j = 0; j
20 Apr 2014 by Dave Kreskowiak
You cannot thread this. All controls and their creation must be on the UI (sometimes referred to as the "startup") thread.You can create controls on different threads and they may even appear to work, most of the time. But you will get the weirdest, unreproducable bugs when using the...
5 May 2014 by OriginalGriff
10 milliseconds is pretty good, in Windows terms - it isn't a real-time operating system, and there is no guarantee that even on the same thread one instruction will be executed immediately before the next: it depends on the system load and can be any time interval at all. Windows is a...
27 Feb 2015 by Sergey Alexandrovich Kryukov
,The only exception you can seed into some working thread totally asynchronously to this thread is the System.Threading.ThreadAbortException, which is done only by runtime system as a result of thread...
30 Dec 2015 by Daniel Pfeffer
I assume that:1. All projects are run as parts of a single process.2. No other synchronization is performed between project2 and project3 (i.e. they don't hold any other synchronization objects when calling WriteData()).If either assumption is false, you will probably need a different...
18 Nov 2019 by Michael Adaixo
Parallelizing ray tracing in C++
7 Dec 2010 by Andrew Phillips
I guess what people were trying to get through to you is you should not care. Multiple threads are used to simplify the design of software that needs to do more than one thing simultaneously. A secondary benefit is improved performance if you happen to be running on a system with more than one...
22 Dec 2010 by E.F. Nijboer
A dll used is normally "in-process" and therefore you could use critical sections. This would not apply if it would be a COM server dll that you use. In that case it would be "out-of-process" and you should use a mutex instead.Good luck!
22 Dec 2010 by Dylan Morley
Pretty sure the DLL is loaded into the application process and all threads are created within that Download Process Explorer http://technet.microsoft.com/en-us/sysinternals/bb896653[^] and you can browse the threads your process has created (invaluable tool if you don't have it...
8 Feb 2011 by Sergey Alexandrovich Kryukov
Answering follow-up question (added to original question after [EDIT])…Some detail of the right design should highly depend on unknown "signal like semaphore concept I think" and on how you do transactions, in other words, on transactional properties.However, even now it's clear...
8 Mar 2011 by Sergey Alexandrovich Kryukov
This is perfectly expected and even desirable result. It does not depend on how many cores you're running, the same effect you can expect even on a single-core single-CPU computer. It looks like you don't want parallel execution in this case, why using thread then?If you explain your...
8 Mar 2011 by Olivier Levrey
If you want the output to display 100, 200, ... as you explained, then you need to wait for all threads to finish before printing the output, then start the next ones, and so on.SA is right: it means you don't need theads at all in your scenario.By the way, you should also initialize num...
9 May 2011 by Olivier Levrey
To display your message box from the UI thread, just use BeginInvoke:yourMainForm.BeginInvoke((Action)(() =>{ //all the code here will be executed in the main thread MessageBox.Show("...");}));Where yourMainForm is a reference to your main form. Actually it can be a...
29 Jun 2011 by Not Active
The "proper" number of threads depends quite a lot on the situation and usage. There is no one size fits all answer. May people, especially beginners, think adding more threads improves performance, but can actually have the opposite effect. For a windows app, only one thread can update the...
17 Sep 2011 by Randor
James,The Microsoft GDI+ library gdiplus.dll will spawn worker threads within your process. I don't think there is any documented way to control this. You can probably verify this by downloading Process Explorer[^] and right-clicking your process and selecting the 'Threads' tab. If you have...
20 Sep 2011 by Manfred Rudolf Bihy
Your two for loops are executed sequentially. Thread.Sleep only waits 10 ms in between adding two items. This has nothing to do with multithreaded programming. For that you'd have to produce two separate Threads and do the adding from there. Please make sure to use Control.Invoke when accessing...
7 Nov 2011 by Danyvaral
i am creating windows application in C# in which i want to write in a multiple file with multiple threads.I am getting data from different ports and there is one file associated with every port.Is it possible that creation of thread for every port and use the same thread again and again for...
9 Feb 2012 by Richard MacCutchan
Trap the key events and store the start time in a table using the keynumber as index. At the keyup event you can calculate (currentTime - startTime = elapsedTime). What is the difficulty?
26 May 2012 by SoMad
I have done a lot of work with RS232 input in my time and I have encountered several pitfalls that I did not expect to stumble across.You are not specifying if you are using a "real" COM port or a USB COM port device. The USB COM port devices are great, but they do not work 100% as a native...
20 Jun 2012 by Sergey Alexandrovich Kryukov
This design is a bit hard to follow. I would advise to use a bit different approach, without using async API. Instead, the application which listens for new connections and performs data exchange on the network (reading/writing from/to network stream or reading/writing form/to a remote socket)...
15 Mar 2013 by Sergey Alexandrovich Kryukov
This is one of the difficult problems. When you exit the application, all other threads should exit their thread functions, otherwise they will hold your application process from terminating.The problem appears when the thread function "never returns", which is a very usual case.The...
7 Apr 2013 by Matthew Faithfull
What you say may be completely correct but I believe the problem goes deeper than one of cache coherency. The issue I think is rather to do with the language specification and the current state of the art in optimising compilers.The C++ language specification does not, contrary to common...
7 Apr 2013 by H.Brydon
The professor was correct.The short answer to your question is that the code sequence illustrated needs to turn the operations into atomic operations which, amongst other things, will flush the cache and disable/workaround the instruction reordering as described.
19 Apr 2013 by Sergey Alexandrovich Kryukov
Are you serious? Most weird idea.Not just yes, but: yes of course. Moreover, if you have an old single-code Pentium-based system, many multithreading OS like Windows or Linux, will perfectly work on it. I even have a couple of such systems under my control; they work very well.By the...
1 May 2013 by CPallini
Create an array of thread procedures, for instance:DWORD WINAPI myThreadProcA(LPVOID p){ DWORD dw = (DWORD) p; return dw;}DWORD WINAPI myThreadProcB(LPVOID p){ DWORD dw = (DWORD)p; return dw*dw;}VOID CreateMyThreads(LPTHREAD_START_ROUTINE myProc[], int max_number,...
25 May 2013 by Espen Harlinn
None of them, if you are lookig for optimal parallelization you are looking for ways to avoid sychronization between the worker threads. Best regardsEspen Harlinn
18 Sep 2013 by pdoxtader
"I would like to know if it is possible to have a multithread application that does a copy process of about 20GB of files from a source folder to a destination folder"- Yes. I actually took the time to write one... tweak it so that people could use it to create batch jobs... adjust how many...
19 Sep 2013 by Dave Kreskowiak
What noone here has mentions is that multi-threading your copy operation may be a complete waste of time depending on your disk configuration.If you're running a disk array then the copy operation might speed up a bit (don't expect orders of magnitude performance increases!) because...
16 Nov 2013 by Sergey Alexandrovich Kryukov
Very bad, wrong pattern which does not cause deadlock but is the total waste of CPU time. Besides, x is supposed to be used as a shared variable (otherwise it the loop will never break), and the access to it is not interlocked, while cond.lock is simply irrelevant. Wasting of CPU time may or may...
8 Jan 2014 by Ravi Bhavnani
You should educate yourself on the general principles of client-server apps - that would help you design a solution. There's no need to create multiple servers. A single server that offers multiple services (e.g. for chat, for retrieving a poker hand, for making plays, etc) will suffice./ravi
13 Feb 2014 by Jochen Arndt
Your code may access uninitialized memory.Your loops run up to numOfChunks inclusive where numOfChunks is file size / chunk size (I would expect '
5 May 2014 by Dave Kreskowiak
On top of OriginalGriff's response, which is dead on accurate, I don't think you're going to get away with using a couple of USB webcams to do this. Since you can't get data simultaneously from two devices on the same USB controller at the exact same time (refer to what USB stands for:...
23 May 2014 by Sergey Alexandrovich Kryukov
The answer is actually in the comment to the question written by Zeee-M and myself.This is what you can use:...
12 Aug 2014 by Simon_Whale
you could set the MaxDegreesOfParallelism[^] option in your Parrallel.For loop.Alternative options I could suggest is look at the Threadpool Class as you are also able to limit the number of threads that it manages.ThreadPool.SetMaxThreads[^]
18 Jun 2015 by Frankie-C
The differences are in the way that the access to resources is guarantee, and CPU usage.If you use a global flag you have to guarantee that the access is made by a single thread at time. Imagine that your first thread read the flag, then while it is evaluating the status the executing thread...
11 Aug 2015 by Sergey Alexandrovich Kryukov
Ridwan Sameer asked:But the drawing of the car object will be separate from passing the object yes? (I.E even though I pass the object from one thread to another, does not mean the object would be drawn at the appropriate panel)This is yet another chapter you need to learn. It depends on what...
9 Feb 2016 by Dave Kreskowiak
I would probably have a component that manages a queue, loading it with the file paths to process. This component would hand out a file path to process to a worker thread that does all the work for a single file. You can have as many of these worker threads running as there are cores available...
29 Apr 2016 by OriginalGriff
A better method for safety critical systems is true redundancy: Redundancy (engineering) - Wikipedia, the free encyclopedia[^]The hardware is duplicated, the software is written by different teams, and two out of three can "out-vote" the third. Purely duplicating the same calculation in...
31 Oct 2016 by Jochen Arndt
I have not used ReadDirectoryChanges so far but it should be sufficient to call it only once outside the loop. That should solve the problem.If not, you have to wait for both events using a single call. But I recommend to do that anyway:HANDLE ahWait[2] = { p.hEvent, ovl.hEvent };BOOL...
22 Dec 2016 by CPallini
Usually the thread functions must have a fixed signature, for example, on WindowsDWORD WINAPI MyThreadFunction( LPVOID lpParam )Using the lpParam you may pass whatever you need (it is just a matter of cast, see Creating Threads (Windows)[^] ).
17 Jul 2019 by ireland94
This program demonstrates the methodology needed for by directional messaging between a Java FX foreground and 1 or more background threads.
25 Nov 2017 by OriginalGriff
You need to create two threads, each with a different task: one adds even numbers, one add odd. You will need to add the global variable, and provide locking to ensure that the two threads don;t get in a mess while using it. You will also need to provide a signaling mechanism that gets the main...
25 Jan 2018 by Nazar.Bukhari
An article on how to implement Observer Design pattern in Mutithreaded Java application when Function pointer is needed
4 Mar 2018 by Jon McKee
var results = from myRow in dtTaskandBugs.AsParallel() select myRow; results.ForAll(r => { r["Storyid"] = GetStoryid(r["Id"]); r["FeatureID"] = Fidname(r["Storyid"]); r["FeatureName"] = r["FeatureID"].ToString() == "0" ? "Anonymous" : ...
30 Aug 2018 by Rick York
In my opinion, having all the threads write to the same file is unnecessarily complicated. I would make a 1KB buffer and a custom routine to write your data into it with a mutex or critical section to control access. Your threads can write into the buffer until its full at which time the...
3 Aug 2023 by OriginalGriff
If the third party is using static methods, then a second Process environment is the simplest (and probably only) alternative - you can do it fairly easily using the Process class to activate an exe and it gets a separate environment even if the...
11 Nov 2010 by E.F. Nijboer
What I can imagine is that you already set it to be the datasource of a datagrid (or any other UI component) and because you are updating the data, the UI control halts and waits for completion. With this method it prevents updates while executing an update (or any other action). I think you can...
28 Nov 2010 by DaveAuld
If you are using a single static linked list for all the threads to offload onto, then the likelihood is they are having to wait for each other to finish and the linked list is released for the next one to write to.You will have to come up with another mechanism for all the data to be...
29 Nov 2010 by Indivara
There's a sample on MSDN. Seek and ye shall find.
7 Dec 2010 by Rajesh R Subramanian
I'm in agreement with Andrew.You will never need to worry about thread execution at this level of detail. The OS is good enough to ensure that no resources (like a core) will be wasted sitting idle, while a thread is waiting for CPU cycles.
20 Dec 2010 by nortee
Hello,I've found that using the Indy components that come with Delphi work quite nicely for anything to do with socket programming. There are a few demos that come with it as well including emailing, FTP, TCP/IP and more. If your version of Delphi does not have these demos you should be able...
5 Jan 2011 by la_morte
HelloI'm a beginnerI need help how to implement an console with filesystemwatcher that capture created files and another thread (process) that move those files on intranet (with a slower connection)I'm Lost on this code:1 pass:FSW capture files and added those files on...
16 Jan 2011 by #realJSOP
BTW, is this unmanaged code, or .Net?You can't run a DLL as a process. I had to do the same thing a bunch of years ago, and I just used interprocess comms by sending registered messages back and forth between the apps. You can send pointers to strings between the apps. There are a number...
16 Jan 2011 by Espen Harlinn
ACE[^] has just what you need - a flexible robust mechanism for loggingHere is a wee bit of info on Using the ACE Logging Facility[^]From your description, I would guess you could benefit from using ACE in a number of other ways too :)RegardsEspen Harlinn
28 Mar 2011 by Kythen
If you're using .NET 4 you can use the System.Collections.Concurrent.ConcurrentQueue(T)[^] class.If you're using .NET 3.5 or older, you could maybe create a derived class from System.Collections.Queue(T)[^] and employ a System.Collections.Generic.SynchronizedCollection(T)[^] instance...
28 Mar 2011 by Sergey Alexandrovich Kryukov
You naive "implementation" if mutual exclusion is incorrect (it does not guarantee mutual exclusion) and cannot be accepted for performance reason: it will occupy 100% of CPU time of one of the cores without a reason. It is called spin-wait which never should be used. All waits should be done on...
15 Apr 2011 by Albin Abel
Here is an example code.public class ThreadTest{ private string _file="Hello World"; private ReaderWriterLock _rw1=new ReaderWriterLock(); public void ReadFile(object obj) { _rw1.AcquireReaderLock(1000); for(int i=0;i
15 Apr 2011 by Albin Abel
9 May 2011 by Sergey Alexandrovich Kryukov
Please see my comments to the solution by Olivier.Here is one resolution: have a shared instance of System.Threading.EvenWaitHandle and make is reset before handling exception. In the thread handling exception, use Dispatcher.BeginInvoke and immediately call EvenWaitHandle.Wait. This thread...
9 May 2011 by Espen Harlinn
The DispatcherSynchronizationContext Class[^] provides a synchronization context for Windows Presentation Foundation (WPF).You'll find an example here: Task Parallel Library: 1 of n[^]RegardsEspen Harlinn
20 May 2011 by Albert Holguin
This is trivial, if you don't terminate a thread properly, all of its internal memory will leak. Terminate properly and it won't be an issue.
30 May 2011 by Timberbird
1. You can duplicate thread handle and use it with WaitForSingleObject() function as described here[^]. Generally (regarding other cases, when you just need to wait for some time - your listeningThread function, for example), using Sleep() is not recommended, consider using WaitForSingleObject...
8 Jun 2011 by Espen Harlinn
As Niklas Lindquist mentions: If the data is availalbe in memory before the threads start - possibly using a memory mapping - and the data is not altered by the threads. there is no need to protect the memory using a locking mechanism, just access at will. If each thread writes it's results to a...
21 Jun 2011 by SergeyT2
You can use Action instead of MethodInvoker as well. And ".Invoke" at the method is unnesessary.public static void ThreadSafeCall(this Control control, Action method){ if (control.InvokeRequired) { control.Invoke(method); } else { method(); ...
3 Jul 2011 by Sergey Alexandrovich Kryukov
Your goal is not loading about 100% of the core but improving throughput of application and responsiveness of the system. Actually, using 100% of the core by some UI application is more typically a sign of abuse of programming technique and extremely bad quality of the code.If you don't...
25 Jul 2011 by #realJSOP
Add a menu item to your File menu with the label "Open New Instance...", and when the user slects the file to be opened, spawn a new process.I shouldn't have to say this, but if I don't someone else will...That's a fairly bizarre requirement since an MDI app, by it's very nature, allows...
11 Aug 2011 by Christian Graus
This is not a bug in the framework, you're just not using these things properly. You seem to be calling Invoke, so I'm not sure why you'd get an exception, unless you have code that sets the progress bar ? I don't recognise what your code is doing when it calls invoke tho, it should invoke the...
20 Sep 2011 by Sergey Alexandrovich Kryukov
In addition to the solution by Manfred: please see my recent solution where I explain invocation using both Control and also Dispatcher: Is this correct coding?[^].—SA
7 Nov 2011 by Sergey Alexandrovich Kryukov
It's not a bad idea to reuse threads. You have two options: 1) using thread pool, 2) having "permanent" thread (with lifetime maybe close to the lifetime of your process) pushing different tasks on it when required and throttling it between tasks the way it spend not CPU time and waits to be...
4 Dec 2011 by Member 8002808
Hello everyoneI Have read several articles about multithreading in C# WPF. Some recommend using BackgroundWorker some threading. Most are not clear enough. Can anyone clearly explain multithreading with a simple example that someone like me with least amount of experience in programing can...