Click here to Skip to main content
15,885,216 members
Everything / General Programming / Threads

Threads

threads

Great Reads

by Maxim Kartavenkov
Articles describes how to create virtual video capture source directshow filter in pure C#
by Maxim Kartavenkov
Article describes how to make H.264 Video Encoder DirectShow Filter using NVIDIA encoder API in C#
by Sergey Alexandrovich Kryukov
Addresses questions on graphics, threading with UI, form development, printing and more
by honey the codewitch
Take control of which thread your code gets executed on, and how it does

Latest Articles

by Bruno van Dooren
What to do when you want to use the current thread handle
by Bruno van Dooren
How to implement named pipe server for communicating with client apps
by Bruno van Dooren
How to implement named pipe server for communicating with client apps
by Greg Utas
Keeping a program running when it would otherwise abort

All Articles

Sort by Updated

Threads 

12 Nov 2023 by headshot9x
I have a WinForms application C#. In here, I used TcpClient/Socket and NetworkStream. I have created multiple thread to handle sending/receiving from client/server. Assuming I'm forced to use TcpClient/Socket, I won't use other libraries or...
29 Jul 2023 by rain-13
I want to compute multiple hashes for image. to speed it up I want to compute all hashes in parallel. I have method called hashImage which returns dictionary. Expected result is that all dictionary keys have values that are other than None....
18 Jul 2023 by kavinderrana121
Facing deadlock issue in below program, The same instance of below class will be passed to three different thread one is responsible for printing 0, and one for even num and other for odd. After printing 0 1 it print killed and terminates. In...
18 Jul 2023 by CPallini
In your case, the debug is simple, just by inspection: the zero method (t1) unlocks sOdd and then exits. Then the odd method (t3) terminates (because sOdd is unlocked). The even method has no chance to exit, because sEven is still locked. You can...
16 Feb 2023 by Member 15926793
Hi, I have started to study thread on c language. I develop code, Now I want to add threading part with queue which continuously polling if info is coming or not. Can anyone suggest where do I start ? I'm not asking for the code but just idea...
16 Feb 2023 by OriginalGriff
Strat by reading up on threading: it's not as simple as it appears. Here's a few links to get you going: https://dev.to/quantumsheep/basics-of-multithreading-in-c-4pam[^] Multithreading in C - GeeksforGeeks[^] - those are C language specific and...
16 Feb 2023 by CPallini
A starting point: Producer–consumer problem - Wikipedia[^].
22 Jan 2023 by merano99
A C++ std::mutex instance is limited to a single process; if you need cross-process mutexes, as here, you could use operating system semaphores or, under Linux, Posix mutexes in shared memory. If the first process sets a system-wide mutex...
21 Jan 2023 by CoadyCoder
Create a global mutex, this will help us to identify if another instance of the same application is running, this is needed as its inter process communication. 3. Start a thread which runs continuously with a sleep of 1 sec and write "Worker...
21 Jan 2023 by Andre Oosthuizen
Richard is so right!!, you might take a project away from someone else that understands the code or have more experience than yourself, causing them harm. That been said, here is examples in C# and C++... Using C# using System; using...
20 Jan 2023 by Richard MacCutchan
If you cannot complete the task yourself then you obviously do not have the level of experience that this company is looking for. And if someone here provided you with a complete solution and you got the job - what then? When they gave you a real...
27 Dec 2022 by Bruno van Dooren
What to do when you want to use the current thread handle
22 Dec 2022 by Bruno van Dooren
How to implement named pipe server for communicating with client apps
9 Dec 2022 by Bruno van Dooren
How to implement named pipe server for communicating with client apps
14 Oct 2022 by wehrbar
Thank you both, but I have found the solution to my issue. However, to give some background to the context, the Federal Government releases a PDF document (and it is ONLY available as a PDF document) of a list of about 20k financial products....
14 Oct 2022 by wehrbar
I have an UI with a list view control on it that loads several thousand lines of data across about 50 columns. This is easy to export to Excel directly from the UI since the ListView lives on the UI thread, but I would like to create a separate...
13 Oct 2022 by OriginalGriff
To add to what Dave has - rightly - said: you should never throw "thousands of lines" at a user anyway: it's slow, inefficient, and for the user completely useless - how long do you think it's going to take a user to find the row he is interested...
13 Oct 2022 by Dave Kreskowiak
You don't. You cannot touch a control from any other thread other than the UI (startup) thread. You're using the ListView control as a container for data instead of its intended purpose of displaying and editing data. You should be holding all...
9 Oct 2022 by Thodoris Spirantis
I searched on similar cases but i didnt find one that corresponds to the way i set up my application. In the below code, i call a QtWidgets.QDialog class from my main window. And after a button is pressed a heavy operation is starting. My problem...
23 Sep 2022 by mayaduc
Hello everyone, I am new to programming and currently I am creating an application using python and PyQt with controller/joystick, using the pygame library. When I integrated the controller module, I created a while loop to handle all...
20 Sep 2022 by sabin 2021
Ok so I am trying to send 2 objects to a worker thread ( one string and one array), the issue is that I can only send one object thru workerData. What I have tried: So I have tried creating a second constant called workerData2 and send an...
18 Sep 2022 by Death Smoke
#pragma once #include using namespace std; namespace Project1 { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace...
31 Aug 2022 by Reza jafery
To run a single instance of a program, I use the following approach, which is recommended in this link rather than the approach presented here. using System; using System.Reflection; using System.Runtime.InteropServices; using...
30 Aug 2022 by Dave Kreskowiak
string AppGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); What is going to hinder your debugging, and therefore make your code unsupportable, is that you're...
30 Aug 2022 by OriginalGriff
Simple: GetCustomAttributes is returning an empty collection, so your attempt to get the zeroth element is failing. Use the debugger to find out why for your app, we can't run your code under exactly the same circumstances you can.
27 Jun 2022 by Greg Utas
Keeping a program running when it would otherwise abort
17 Jun 2022 by Mircea Neacsu
C++ thread objects and their use
14 Jun 2022 by Greg Utas
Cleaving the Gordian knot of thread safety
11 Jun 2022 by oronsultan
Hi Gyus, We have a service in IIS and we want to perform a certain check every time someone calls one of our APIs, no matter which one. To that end, we registered for the Global_AuthenticateRequest event in the Global.asax file of the service, as...
2 Jun 2022 by Greg Utas
I'm porting a C++ program that runs on Windows to WSL/Ubuntu. It's multithreaded, and all application threads run at the same priority. However, one thread needs to run at priority+1, and another at priority+2. Round-robin scheduling is also...
2 Jun 2022 by k5054
Two things: 1) setcap only seems to apply to the current executable. 2) You can't get the desired behavior using GDB, even using sudo For example, using the following simple C program #include #include #include...
12 Mar 2022 by Southmountain
I test an example from this article. I wrap the logic into a console program as below, but it does not print out any message. where is wrong? I can not figure it why: using System; using System.Collections.Generic; using System.Linq; using...
12 Mar 2022 by RickZeeland
The code works (.NET 4.7.2 and Windows 10) but the output is not sent to the console, so just use: Console.WriteLine(strMessage); instead of: Trace.WriteLine(strMessage);
12 Mar 2022 by OriginalGriff
Don't post this under Quick Answers - if you got the code from an article, then there is a "Add a Comment or Question" button at the bottom of that article, which causes an email to be sent to the author. They are then alerted that you wish to...
4 Mar 2022 by Southmountain
I tried a simple demo at an article on here, and got into an issue, which I think it is simple: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; ...
4 Mar 2022 by OriginalGriff
ref is a keyword: you can't use it as a variable name: IAsyncResult ref = delInstance.BeginInvoke(100,"I am in Delegate Thread", null, null); Change the name, it should compile.
22 Feb 2022 by Member 15390900
Can someone help me achieve thread - safe code of the following code: without using mutex or semaphores or synchronous block. Locking and Unlocking of Resources arranged in the form of n-ary Tree - GeeksforGeeks[^] Calling lock or unlock from...
22 Feb 2022 by I_M_R
Hello, the purpose of using mutex and semaphores are sharing a resource between threads and or processes. In multithread application without using mutex or semaphores one can not reserve that resource into the thread first getting permission and...
18 Feb 2022 by Sean Hull
I have a connection routine that attempts to connect to the ftp server. I have a decent handle on that. My issue is that it only catches exceptions during the connection. I need to watch the connection and catch anything that might happen...
4 Feb 2022 by Member 15524230
I had tried background worker, thread and task but the procedure are so long to get a solution according to my question. suppose I use a task, I can't add any textboxes in ABC function which is called in button_click. When I use textbox inside...
4 Feb 2022 by OriginalGriff
Your "small sample" of code will not work. You can't add an infinite amount of data to a Text box, Rich or not: each time you try, you create a new string which is longer than the last, and cause a Paint event to be queued on the TextBox - which...
27 Dec 2021 by Admin BTA
So I have an event that does some processing and one of the lines in the event takes a long time to complete thus the stuff that happens in the event, very undesireably. Is it common practice to separate out the thing that takes long (in this...
27 Dec 2021 by k5054
That largely depends on what else is going on in you program. For example, lets assume that the time-consuming code (TCC) takes 90% of the time needed for the procedure to complete. Handing that section off to a separate thread isn't going to...
23 Nov 2021 by George Swan
//add 'async' to the method declaration private async void Srv_OnSensorStatusEvent(SensorStatus sensorStatus) { //await for the asynchronous method to complete and unwrap the Task //that is returned from the 'Server.GetSensorById'...
23 Nov 2021 by oronsultan
Hi, Lets say I have a sensor class manager (SensorServer). Inside that class I have an event that helps me receive status changes regarding the sensor: public event OnSensorStatus OnSensorStatusEvent; In my view model (EventsMgr.cs), I create...
28 Oct 2021 by Patrick Skelton
When I lived in the C++ world, I found the subject of threading intuitive. Here in C#, I find I get completely lost, because there seems to be so many ways to do things. Task is probably the best choice most of the time but these are now so...
28 Oct 2021 by Richard Deeming
How about something like this? public class AudioPlayer : IDisposable { private CancellationTokenSource _tokenSource; private void CancelFade(CancellationTokenSource newTokenSource) { var oldTokenSource =...
26 Oct 2021 by Greg Utas
The right side of this page contains links to "Related Questions". You may find some useful information there. It isn't even obvious to me, depending on what f() and g() do, that parallel execution will produce the same result as serial...
26 Oct 2021 by Member 15407141
I have given the following 2 snippets: snippet(1): int i=0; while(i
25 Oct 2021 by Richard MacCutchan
There is not space or time here to teach you how to modify that code so it uses threads. See std::thread - cppreference.com[^].
24 Oct 2021 by Member 12885549
I have a following task: "Ordinary" semaphore Initialized to the number of available resources. operations: request () - waits until the resource is released, release () - releases the resource, numberAvailable () - returns number available...
16 Oct 2021 by Member 14779522
//// serverstartThread.h #ifndef SERVERSTARTTHREAD_H #define SERVERSTARTTHREAD_H #include #include #include "QThread" #include "listenerthread.h" class ServerStart : public QObject { Q_OBJECT signals: ...
12 Oct 2021 by Greg Utas
You could use an atomic[^] rather than a mutex. That's the only thing I can think of that's faster. The entire tree must be locked because it's in a transient state until all of the ancestors have been updated. When using an atomic, a thread...
11 Oct 2021 by Richard MacCutchan
The web page already has some suggested solutions, so follow those.
25 Sep 2021 by temchik_ggg
I've wrote this code: #include #include using namespace std; #define ll long long #define ull unsigned long long #define ld long double const int mx = 1e9; void f(int l, int r, int *res) { int c_3, c_5; c_3 = c_5...
25 Sep 2021 by Richard MacCutchan
Did you include -pthread in your compile options as stated at pthread_create(3) - Linux manual page[^].
24 Sep 2021 by Member 12885549
I have to check unsynchronized and synchronized methods and I decided to do that with following problem: let's say there're two purses and I am adding money to one, , adding to other. When thread is not synchronized I expect not correct values...
24 Sep 2021 by George Swan
I am not sure what you are trying to do but if you wish to update a shared variable from different threads, here are a couple of suggestions. For simple operations like addition or incrementing use the Interlocked class, it is very efficient. ...
24 Sep 2021 by Dave Kreskowiak
Why would the results be 10 and 200? Look at your Add() code in the Purse class. You're adding from 1 to
24 Sep 2021 by Richard MacCutchan
Console.WriteLine($"Purse 1: {purse1.Total}"); Console.WriteLine($"Purse 2: {purse1.Total}" + Environment.NewLine); ^ should be purse2
24 Sep 2021 by mirajanata
The results might be incorrect when two or more threads read and write into the same value or object (memory) without synchronization. Your code creates 2 threads. Each of them works with different object (purse1, purse2). There's no memory...
24 Sep 2021 by OriginalGriff
Why should the result be 10 and 200? You start coinThread before you start purseThread1 - so if your system has spare cores it's very likely that coinThread will complete before purseThread1 even starts! Try adding some Console.WriteLine calls...
16 Sep 2021 by Hadrian Chong
I was designing the airport simulation. After the planes had accessed the runway and landed at the gate, I want it to release the runway where other planes are able to access the runway one at a time. What I have tried: package...
10 Sep 2021 by Nick_is_asking
Hello everyone.I have a problem. (In main): I create 5 threads that put 1 item (at a time) in a rack and 5 threads that get 3 items (at a time) from the rack. So,the threads that get items ,have to wait the rack to fill and when the rack has >=...
10 Sep 2021 by KarstenK
When you get from the reck it gets empty and your get function is exiting. Than you only fill the reck. void *get_from_the_rack(void *arg) { pthread_mutex_lock(&mutex_item__); while(num_of_items
10 Sep 2021 by k5054
The function get_from_the_rack() returns after extracting 3 items, so at most you will remove 15 items from the stack. You need to either wrap the body of get_from_rack() in a loop that tests for some sort of end-of-processing condtions (e.g....
5 Sep 2021 by CPallini
See, for instance: Interlocked Class (System.Threading) | Microsoft Docs[^].
3 Sep 2021 by mverbeke
Main is a static method. The easiest way to do what you are describing would be to create a class to contain your while loop (the control thread) and then a class for your thread. In the constructor for your thread class, pass a reference to...
28 Aug 2021 by Mohammad Elsheimy
SynchronizationContext class and how it affects code behavior in action, and a look at Task.ConfigureAwait()
20 Jul 2021 by Dasisqo
Thread is slower, timeout is set to 13 seconds What I have tried: for i in range(400): try: thread=consumer(quee) thread.setDaemon(True) thread.start() thread.excepthook() except: print "Working only with %s threads"%i...
20 Jul 2021 by k5054
Python is limited by the Global Interpreter Lock (GIL), which only allows one thread to execute at a given instance. This means that threading does not reduce program run times, regardless of how many cores your system has. There's a Stack...
20 Jul 2021 by Dave Kreskowiak
Creating 400 threads does nothing but slow your workload down. The system can only execute the same number of threads as you have cores in your CPU, usually 8 or less unless you have a higher-end CPU. So, creating 400 threads is pointless. There...
20 Jul 2021 by Dasisqo
for i in range(400): try: thread=consumer(quee) thread.setDaemon(True) thread.start() thread.excepthook() except: print "Working only with %s threads"%i break
20 Jul 2021 by Dasisqo
I am very much new to coding python script, i wrote a code in python where the functions can scan a list of remote target but the threads dies quick, The problem is that the thread dies and code ends before the scan is entirely complete. What I...
20 Jul 2021 by Richard MacCutchan
You need to ensure that the main thread of your program does not terminate while child threads are active. See threading — Thread-based parallelism — Python 3.9.6 documentation[^]. [edit] Note also that trying to run 400 threads together will...
10 Jul 2021 by aakar
We are calling a Rest API URL via the HttpWebRequest / HttpWebResponse method using IDs that are already stored in a database table. We am currently using a for each loop to iterate through each of the IDs fetched in a DataTable and then making a...
6 Jul 2021 by Member 15277469
The example shows a small application which should run multi-threaded to speed up the data processing. There is an input-thread, creating work and putting it into a queue created with Thread::Queue A bunch of worker threads is getting started,...
6 Jul 2021 by k5054
Perl threads, at least in perl 5, aren't really threads - they're perhaps more like fibers that are controlled by the perl runtime rather than POSIX or other threads. In general, you will get much better performance using a fork rather than...
19 Jun 2021 by Chetan Kudalkar
Meaning of synchronized keyword with a deeper look
16 Apr 2021 by Chris_Green
Get an event fired by Thread A to execute in the context of Thread B
15 Apr 2021 by DeepsMann
Hye,1. I have to program a server which can listen multiple clients on a single port (say 8080).2. Once connection is established with a client, communication starts between client and server. Client sends - Server Receives, then Server sends - Client receives.3. If multiple Clients are...
6 Apr 2021 by Jason Sultana
In this post, you will see why Threadsafe is not enough
19 Mar 2021 by Greg Utas
SIGSEGV means that you dereferenced an invalid pointer, most often one that was NULL or uninitialized. EDIT: To follow up, let me start by saying that I haven't used this pthread stuff. But the following looks suspicious: pthread_mutex_t...
19 Mar 2021 by Nick_is_asking
Hello everybody.I have an exercise (kiwi engine) in university (OS course) and I have to use thread. The code is big (10.000 lines) and I only have to use threads to make it faster. In the following code if you can see a comment like: //...
10 Mar 2021 by Nick_is_asking
Hello.I have a small program.I have to create 2 threads in order to increase a global variable until 20 (for example).At the same time I want my 3rd thread (3 threads total) to wait until global variable reach the number 20.if number is 20,then...
10 Mar 2021 by CPallini
Try, for instance (see Using Condition Variables (Multithreaded Programming Guide)[^]) #include #include pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *...
1 Mar 2021 by MehranSarrafi
Hi In the C# program, I want to call a function to screen capture and save it to the database, when an exception occurs and the program is in a stopped mode. What I have tried: Hi In the C# program, I want to call a function to screen capture...
1 Mar 2021 by MehranSarrafi
Thanks, I found out my solution and I write down here; and I hope it will be useful for others. I catch the exception with try catch block and call my function to do what I need in a new thread; and then throw the exception again with the main...
27 Feb 2021 by honey the codewitch
Using a popular RTOS to enable easy multithreading on your IoT gadgets
25 Feb 2021 by honey the codewitch
Take a page from .NET and enjoy an easy way to safely pass information between threads on an ESP32
23 Feb 2021 by OriginalGriff
If your app has stopped, you can't do anything: you need your code running in order to do anything. So by that time, it;'s too late - the idea is to spot problems before they become fatal, and do something useful then; then continue or fail the...
11 Feb 2021 by Member 12745186
in my asp.net web application, I have a process that is run on the thread and my requirement is to add a Stop Process button which will stop the all running thread which is created inside that method only and I also want to end the process...
1 Feb 2021 by Member 14530069
Hi, i try to use watson to send a callback. Whatson is buildt to create asynchronous connections. My question is, how can i handle the request. Like i expected it appears that the result is not here. Because the Server continues on a other...
1 Feb 2021 by CHill60
I'm afraid your question cannot really be answered in a "quick" answers' forum - you have not provided sufficient code nor an adequate description of your problem. In response to the title of your post however, I suggest you try the resources at...
29 Jan 2021 by FGonzalezGenta
Hello guys, I need help. I'm trying to develope a modbus poll program to read an energy metter. The thing is that I'm using a WF program that I found and trying to convert it to WPF. Please take a look at it: using System; using...
29 Jan 2021 by FGonzalezGenta
Hello guys, I already solved it!! I just had to put some lines between this: this.Dispatcher.Invoke(() => { // (CODE) }); Just for being clear, I'll put the complete program below, you can use (CTRL + F) to find the place where I put...
29 Jan 2021 by CPallini
Did you try Googling for (wpf - How to deal with cross-thread access exceptions? - Stack Overflow[^])?
19 Nov 2020 by viki_10
typedef std::function ConsumerCallback; class first { void ConsumeMessage(ConsumerCallback callback); }; void ConsumeMessage(ConsumerCallback callback) { .... used ConsumerCallback } class second { void...
19 Nov 2020 by Shao Voon Wong
You can use C++11 thread, instead of boost thread because it supports lambda which made life working with thread, a lot simpler. You should separate the callback passing and real work into 2 functions. std::thread *startThread= new...