Threads in C in Windows - c

The perfect way to run and terminate threads in Windows using C is mentioned in the answer below!
There are 2 problems I'm facing with the current implementation method :
I can't forcibly stop the thread. For some reason it still continues. For example I have a for loop, it runs a function of which this thread example is a part. When this function is called 4-5 times, I see multiple animations on the screen suggesting that the previous threads didn't stop even when I called TerminateThread function at the end of my function.
At times the thread doesn't run at all and no animation is displayed on the screen. Which is if my function code runs really fast or for some other reason, I feel like the thread is being killed before it initializes. Is there a way to wait until init of thread?
How do I fix these issues?

Correct way of terminating threads is to signal the thread and let it finish gracefully, i.e.:
(updated to use interlocked intrinsics instead of a volatile flag, as per #IInspectable's comment below)
HANDLE eventHnd;
HANDLE threadHnd;
LONG isStopRequested = 0; // 1 = "stop requested"
static DWORD WINAPI thread_func(LPVOID lpParam)
{
do
{
// wait until signalled from a different thread
WaitForSingleObject(eventHnd, INFINITE);
// end thread if stop requested
if (InterlockedCompareExchange(&isStopRequested, 0, 0) == 1)
return 0;
// otherwise do some background work
Sleep(500);
} while (true);
}
The eventHnd variable is initialized using the CreateEvent function, and the stopRequested variable is just a boolean flag you can set from your main program:
// this creates an auto-reset event, initially set to 'false'
eventHnd = CreateEvent(NULL, false, false, NULL);
InterlockedExchange(&isStopRequested, 0);
threadHnd = CreateThread(NULL, 0, Processing_Thread, NULL, 0, NULL);
So, whenever you want to tell the thread do perform a task, you will simply set the event:
SetEvent(eventHnd);
And when you want to end the thread, you will set the flag to true, signal the event, and then wait for the thread to finish:
// request stop
InterlockedExchange(&isStopRequested, 1);
// signal the thread if it's waiting
SetEvent(eventHnd);
// wait until the thread terminates
WaitForSingleObject(threadHnd, 5000);

Related

Correctly waiting for a thread to terminate in C

This code plays a sound clip by creating a thread to do it. When bleep() runs, it sets the global variable bleep_playing to TRUE. In its main loop, if it notices that bleep_playing has been set to FALSE, it terminates that loop, cleans up (closing files, freeing buffers), and exits. I don't know the correct way to wait for a detached thread to finish. pthread_join() doesn't do the job. The while loop here continually checks bleep_id to see if it's valid. When it isn't, execution continues. Is this the correct and portable way to tell a thread to clean up and terminate before the next thread is allowed to be created?
if (bleep_playing) {
bleep_playing = FALSE;
while (pthread_kill(bleep_id, 0) == 0) {
/* nothing */
}
}
err = pthread_create(&bleep_id, &attr, (void *) &bleep, &effect);
I
Hmm... pthread_join should do the job. As far as I remember the thread has to call pthread_exit...?
/* bleep thread */
void *bleep(void *)
{
/* do bleeping */
pthread_exit(NULL);
}
/* main thread */
if (pthread_create(&thread, ..., bleep, ...) == 0)
{
/*
** Try sleeping for some ms !!!
** I've had some issues on multi core CPUs requiring a sleep
** in order for the created thread to really "exist"...
*/
pthread_join(&thread, NULL);
}
Anyway if it isn't doing its thing you shouldn't poll a global variable since it will eat up your CPU. Instead create a mutex (pthread_mutex_*-functions) which is initially locked and freed by the "bleep thread". In your main thread you can wait for that mutex which makes your thread sleep until the "bleep thread" frees the mutex.
(or quick & and dirty: sleep for a small amount of time while waiting for bleep_playing becoming FALSE)

Event object manual-reset, wrong thread synchronization

I'm approaching to C Windows programming in particular threads, concurrency and synchronization.
To experiment, I'm writing a C program that accepts N parameters.
Each parameter indicates a path to a file system directory tree and the program has to compare the content of all directories to decide whether all directories have the same content or not.
The main runs a "reading" thread for each parameter while a single "comparison" thread compares the name of all the entries found. For each file/directory found, "reading" threads synchronize themselves by activating the "comparison" thread.
I wrote the program with Semaphore objects and now I'm trying with Event objects.
The idea is to use N Events auto-reset and a single Event manual-reset.
The N events are used by the N "reading" threads to signal the "comparison" thread which is in WaitForMultipleObjects for an INFINITE time. When all the signals are available, it starts comparing the entry and then it performs a SetEvent() for the manual-reset object.
The "reading" threads wait for this set and then Reset the event and continue working with the next entry.
Some code for the N reading threads:
void ReadingTraverseDirectory(LPTSTR StartPathName, DWORD i) {
//variables and some work
do {
//take the next entry and put it in current_entry;
gtParams[it].entry = current_entry; //global var for comparison
SetEvent(glphReadingEvent[i]); //signal the comparison thread
WaitForSingleObject(ghComparisonEvent, INFINITE); //wait signal to restart working
ResetEvent(ghComparisonEvent); //reset the event
if (current_entry == TYPE_DIR) {
ReadingTraverseDirectory(current_entry, i); //recur to explor the next dir
}
} while (FindNextFile(SearchHandle, &FindData)); //while there are still entries
//
return;
}
Some code for the comparison thread:
DWORD WINAPI CompareThread(LPVOID arg) {
while (entries are equal){
WaitForMultipleObjects(N, glphReadingEvent, TRUE, 1000);
for (r = 0; r < nworkers - 1; r++){
if (_tcscmp(entries) != 0){
//entries are different. exit and close.
}
}
SetEvent(ghComparisonEvent);
}
}
The problem:
Sometimes it happens that one reading thread is able to work without respecting the synchro with other threads. If I put a printf() or Sleep(1) -between Wait and Set of the comparison thread-, the program works perfectly.
My opinion:
I think the manual-reset Event is not safe for this kind of (barrier)synchronization.
A reading thread may be too fast in ResetEvent() and if the scheduler slows down other threads, it is possible that some of them risk to stay blocked while the one which performed the Reset is able to continue its work.However if this is the case, the comparison thread should block itself on WaitingForMultipleObjects causing a deadlock... actually there is no deadlock but 1 thread is able to cycle more times respect to others.
What I'm trying to understand is why a simple Sleep(1) can solve the issue. Is it matter of scheduling or wrong implementation of synchronization?
Thank you.

Making unknown number of child threads inside parent thread using win32 in C?

How can I make unknown number of child threads inside parent thread and wait for each of them one by one using win32 in C?
The parent thread life time is infinite and it is wait for request and if received any request then make a new child thread for that request e.g. like servers .
I am searching the web but I cant find anything .
Any tutorial and information appreciated .
Thanks a lot , good luck .
note :
1 . For example imagine a simple server : When a user send a request to that server the server make a new thread for that user and wait for that thread to terminated but if another user send another request the server make another thread which is completely separate from the old one and then the server must wait for the new thread separate from the old one to terminate .
2 . The main thread scan an global array with the size of constant n in the infinite loop and if find the specific value in each of array's block then run the new thread to do some operation on that block's information and then after the thread become terminate update that block's information . The parent thread life time is infinite because it has a infinite loop .
You'ld create each thread with CreateThread and store the thread handle in a dynamic list or array. If you want the main thread to recognize when a thread terminated, then you can call WaitForMultipleObjects, providing it an array with all thread handles. The return value of WaitForMultipleObjects will tell you which thread handles was signalled, so which thread terminated. Don't forget to CloseHandle the thread handle at the end.
If you just want to spawn threads and the main thread does not need to know when the threads terminate, then you can just create the threads with CreateThread and close the thread handle. The thread's resources will be freed when the thread terminates.
In your main thread you will also need to check if you receive a client request. If you have an Interface to the client where you can wait on an event, then just add the event to the event array passed to WaitForMultipleObjects. If you do not have an event like in your case 2, then you might consider calling WaitForMultipleObjects with a timeout so WaitForMultipleObjects either returns when a thread terminated or when the timeout occured. In both cases your main loop keeps running and you can check if you need to spawn another thread.
Here is some pseudo code when using an event for the client requests:
initialize empty list of thread data (thread handles and other data for each thread);
for(;;) {
create an array a big enough for the request event and for all thread handles;
a[0] = request event handle;
a[1..n] = thread handles from the list;
DWORD ret = WaitForMultiObjects(n+1, a, FALSE, INFINITE);
if(ret == WAIT_OBJECT_0) {
create thread and store it's handle and other data in the list;
}
else if(WAIT_OBJECT_0 + 1 <= ret && ret <= WAIT_OBJECT_0 + n) {
thread (ret - WAIT_OBJECT_0 - 1) terminated, do your cleanup and don't forget CloseHandle();
}
else
error occured, should not happen;
}
If you don't have an event for the client requests, then you need to poll:
initialize empty list of thread data (thread handles and other data for each thread);
for(;;) {
create an array a big enough for the request event and for all thread handles;
a[0..n-1] = thread handles from the list;
DWORD ret = WaitForMultiObjects(n, a, FALSE, your desired timeout);
if(ret != WAIT_TIMEOUT)
; // timeout occured, no thread terminated yet, nothing to do here
else if(WAIT_OBJECT_0 <= ret && ret < WAIT_OBJECT_0 + n) {
thread (ret - WAIT_OBJECT_0) terminated, do your cleanup and don't forget CloseHandle();
}
else
error occured, should not happen;
// Always check for client requests, not only in case of WAIT_TIMEOUT.
// Otherwise you might run into the situation that every time you call WaitForMultiObjects a thread ended just before the timeout occured and you only recognize it after a lot of loop runs when the last thread terminated.
if(there is a client request) {
create thread and store it's handle and other data in the list;
}
}
If you do not need to store extra data for each thread, then you can just store the thread handles and maybe already store them in a big array. Thus you could eliminate the step to build an array from the thread handle list.
Maybe yo should use the WaitForMultipleObjects function.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx

Unpredictable behavior with SetEvent and WaitForMultipleObjects

I am attempting to use SetEvent and WaitForMultipleObjects so I wrote a couple of functions that I wanted to synchronize using Events. I want the first function to execute, and then signal the second function to execute, which in turn signals the first function to execute again etc.
Two events were created, one initialized to a signaled state, the other unsignaled. The only way I can get the execution to flow as expected is when putting the each thread to sleep for 10 ms. I read about some caveats about using SetEvent:
http://cboard.cprogramming.com/windows-programming/100818-setevent-resetevent-3.html
My question is must I put my threads to sleep because these function calls require extra time to actually signal the events? When debugging sometimes an event that is set still remains unsignalled. I verify this using process explorer. My code basically looks like this:
in the main:
//1. FinCalcpidUpdatestruct << initialize to unsignalled
//2. FinUpdatestructCalcpid << initialize to signalled
FinCalcpidUpdatestruct = CreateEvent (NULL, FALSE, FALSE, TEXT("FinCalcpidUpdatestruct"));
FinUpdatestructCalcpid = CreateEvent (NULL, FALSE, TRUE, TEXT ("FinUpdatestructCalcpid"));
void function1()
{
int n;
int noGoCode;
n=0;
noGoCode = 0;
while(1)
{
//Sleep(10);
noGoCode = WaitForSingleObject (FinCalcpidUpdatestruct, INFINITE);
if (noGoCode == WAIT_OBJECT_0) {
//wait for FinCalcpidUpdatestruct to be signalled
BufferOut[n] = pid_data_array -> output;
//signal FinUpdatestructCalcpid
if(!SetEvent (FinUpdatestructCalcpid))
printf("Couldn't set the event FinUpdatestructCalcpid\n");
else{
printf("FinUpdatestructCalcpid event set\n");
Sleep(10);
}
}
else
printf("error\n");
}
}
void function2()
{
int nGoCode = 0;
while(1)
{
//wait for FinUpdatestructCalcpid to be signalled
// Sleep(10);
nGoCode = WaitForSingleObject (FinUpdatestructCalcpid, INFINITE);
if (nGoCode == WAIT_OBJECT_0) {
if(!SetEvent (FinCalcpidUpdatestruct))
printf("Couldn't set the event FinCalcpidUpdatestruct\n");
else{
printf("FinCalcpidUpdatestruct event set\n");
Sleep(10);
}
}
else
printf("error\n");
}//end while(1)
If the sleep is not used then sometimes the same function will run through the while loop a couple of times instead of ping ponging back and forth between the two functions. Any ideas?
You can fix the problem by adding a printf above the SetEvent call on each function.
The problem is that you are setting the event and then performing some output.
In function2 the printf occurs after the SetEvent:
// Add a printf call here to see sensible output.
if(!SetEvent (FinUpdatestructCalcpid))
printf("Couldn't set the event FinUpdatestructCalcpid\n");
else{
// Thread is pre-empted by kernel here. This is not executed immediately
printf("FinUpdatestructCalcpid event set\n");
}
The kernel preempts the thread running function2 so the FinUpdatestructCalcpid event has now been set, without the corresponding printf that you're expecting.
The thread running function1 is then executed and sets the FinUpdatestructCalcpid event. The thread running function2 is now allowed to execute and continues from where it left off. It runs the printf and because the FinUpdatestructCalcpid event has been set it immediately runs again.
The Sleep() calls you're using help to make this race condition unlikely, but do not eliminate it.
Let me cut your code short for brevity first:
FinCalcpidUpdatestruct = CreateEvent (NULL, FALSE, FALSE, TEXT("FinCalcpidUpdatestruct"));
FinUpdatestructCalcpid = CreateEvent (NULL, FALSE, TRUE, TEXT ("FinUpdatestructCalcpid"));
void function1()
{
while(1)
{
WaitForSingleObject (FinCalcpidUpdatestruct, INFINITE);
// Do Something
SetEvent (FinUpdatestructCalcpid);
printf(...);
Sleep(10);
}
}
void function2()
{
while(1)
{
nGoCode = WaitForSingleObject (FinUpdatestructCalcpid, INFINITE);
SetEvent (FinCalcpidUpdatestruct);
printf(...); // **A**
Sleep(10);
}
}
At basically any point of execution the control might be taken away from thread and given to another. Now suppose that function2 already set the event and is about to print output around **A** in code. Before the output is printed, the control is taken away and given to function1. The last printed output is already from function1 and its wait event is set, so it falls through and prints its stuff again.
When this happens, your output is once in a while:
function1
function2
function1
function2
function1
// When the situation **A** above happens:
function1
function2
function2
function1
// And we move on as usual further
function2
function1
function2
Set your events when you are done, that is after printf, and you will be fine.
Here's what I think...
You don't output any status until you have already set the event. At that point, execution could switch to the other thread before you output anything. If that thread runs first, then it might look as if one thread's loop has run through a second time -- a ping with out a pong...
But if you were to increment a global counter in between receiving a signal and setting an event, then save that counter's value to a local variable, you would probably find that one thread's count is always odd and the other's is always even (which is the behaviour you want), even if the output is not quite in order.

Terminating a thread gracefully not using TerminateThread()

My application creates a thread and that runs in the background all the time. I can only terminate the thread manually, not from within the thread callback function.
At the moment I am using TerminateThread() to kill that thread but it's causing it to hang sometimes.
I know there is a way to use events and WaitForSingleObject() to make the thread terminate gracefully but I can't find an example about that.
Please, code is needed here.
TerminateThread is a bad idea, especially if your thread uses synchronization objects such as mutexes. It can lead to unreleased memory and handles, and to deadlocks, so you're correct that you need to do something else.
Typically, the way that a thread terminates is to return from the function that defines the thread. The main thread signals the worker thread to exit using an event object or a even a simple boolean if it's checked often enough. If the worker thread waits with WaitForSingleObject, you may need to change it to a WaitForMultipleObjects, where one of the objects is an event. The main thread would call SetEvent and the worker thread would wake up and return.
We really can't provide any useful code unless you show us what you're doing. Depending on what the worker thread is doing and how your main thread is communicating information to it, it could look very different.
Also, under [now very old] MSVC, you need to use _beginthreadex instead of CreateThread in order to avoid memory leaks in the CRT. See MSKB #104641.
Update:
One use of worker thread is as a "timer", to do some operation on regular intervals. At the most trivial:
for (;;) {
switch (WaitForSingleObject(kill_event, timeout)) {
case WAIT_TIMEOUT: /*do timer action*/ break;
default: return 0; /* exit the thread */
}
}
Another use is to do something on-demand. Basically the same, but with the timeout set to INFINITE and doing some action on WAIT_OBJECT_0 instead of WAIT_TIMEOUT. In this case you would need two events, one to make the thread wake up and do some action, another to make it wake up and quit:
HANDLE handles[2] = { action_handle, quit_handle };
for (;;) {
switch (WaitForMultipleObject(handles, 2, FALSE, INFINITE)) {
case WAIT_OBJECT_0 + 0: /* do action */ break;
default:
case WAIT_OBJECT_0 + 1: /* quit */ break;
}
}
Note that it's important that the loop do something reasonable if WFSO/WFMO return an error instead of one of the expected results. In both examples above, we simply treat an error as if we had been signaled to quit.
You could achieve the same result with the first example by closing the event handle from the main thread, causing the worker thread get an error from WaitForSingleObject and quit, but I wouldn't recommend that approach.
Since you don't know what the thread is doing, there is no way to safely terminate the thread from outside.
Why do you think you cannot terminate it from within?
You can create an event prior to starting the thread and pass that event's handle to the thread. You call SetEvent() on that event from the main thread to signal the thread to stop and then WaitForSingleObject on the thread handle to wait for the thread to actually have finished. Within the threads loop, you call WaitForSingleObject() on the event, specifying a timeout of 0 (zero), so that the call returns immediately even if the event is not set. If that call returns WAIT_TIMEOUT, the event is not set, if it returns WAIT_OBJECT_0, it is set. In the latter case you return from the thread function.
I presume your thread isn't just burning CPU cycles in an endless loop, but does some waiting, maybe through calling Sleep(). If so, you can do the sleeping in WaitForSingleObject instead, by passing a timeout to it.
What are you doing in the background thread? If you're looping over something, you can end the thread within itself by having a shared public static object (like a Boolean) that you set to true from the foreground thread and that the background thread checks for and exits cleanly when set to true.
It is a code example for thread management in the fork-join manner. It use struct Thread as a thread descriptor.
Let's introduce some abstraction of the thread descriptor data structure:
#include <Windows.h>
struct Thread
{
volatile BOOL stop;
HANDLE event;
HANDLE thread;
};
typedef DWORD ( __stdcall *START_ROUTINE)(struct Thread* self, LPVOID lpThreadParameter);
struct BootstrapArg
{
LPVOID arg;
START_ROUTINE body;
struct Thread* self;
};
Functions for the thread parent use:
StartThread() initialize this structure and launches new thread.
StopThread() initiate thread termination and wait until thread will be actually terminated.
DWORD __stdcall ThreadBootstrap(LPVOID lpThreadParameter)
{
struct BootstrapArg ba = *(struct BootstrapArg*)lpThreadParameter;
free(lpThreadParameter);
return ba.body(ba.self, ba.arg);
}
VOID StartThread(struct Thread* CONST thread, START_ROUTINE body, LPVOID arg)
{
thread->event = CreateEvent(NULL, TRUE, FALSE, NULL);
thread->stop = FALSE;
thread->thread = NULL;
if ((thread->event != NULL) && (thread->event != INVALID_HANDLE_VALUE))
{
struct BootstrapArg* ba = (struct BootstrapArg*)malloc(sizeof(struct BootstrapArg));
ba->arg = arg;
ba->body = body;
ba->self = thread;
thread->thread = CreateThread(NULL, 0, ThreadBootstrap, ba, 0, NULL);
if ((thread->thread == NULL) || (thread->thread == INVALID_HANDLE_VALUE))
{
free(ba);
}
}
}
DWORD StopThread(struct Thread* CONST thread)
{
DWORD status = ERROR_INVALID_PARAMETER;
thread->stop = TRUE;
SetEvent(thread->event);
WaitForSingleObject(thread->thread, INFINITE);
GetExitCodeThread(thread->thread, &status);
CloseHandle(thread->event);
CloseHandle(thread->thread);
thread->event = NULL;
thread->thread = NULL;
return status;
}
This set of functions is expected to be used from the thread launched by StartThread():
IsThreadStopped() - Check for the termination request. Must be used after waiting on the below functions to identify the actual reason of the termination of waiting state.
ThreadSleep() - Replaces use of Sleep() for intra-thread code.
ThreadWaitForSingleObject() - Replaces use of WaitForSingleObject() for intra-thread code.
ThreadWaitForMultipleObjects() - Replaces use of WaitForMultipleObjects() for intra-thread code.
First function can be used for light-weight checks for termination request during long-running job processing. (For example big file compression).
Rest of the functions handle the case of waiting for some system resources, like events, semaphores etc. (For example worker thread waiting new request arriving from the requests queue).
BOOL IsThreadStopped(struct Thread* CONST thread)
{
return thread->stop;
}
VOID ThreadSleep(struct Thread* CONST thread, DWORD dwMilliseconds)
{
WaitForSingleObject(thread->event, dwMilliseconds);
}
DWORD ThreadWaitForSingleObject(struct Thread* CONST thread, HANDLE hHandle, DWORD dwMilliseconds)
{
HANDLE handles[2] = {hHandle, thread->event};
return WaitForMultipleObjects(2, handles, FALSE, dwMilliseconds);
}
DWORD ThreadWaitForMultipleObjects(struct Thread* CONST thread, DWORD nCount, CONST HANDLE* lpHandles, DWORD dwMilliseconds)
{
HANDLE* handles = (HANDLE*)malloc(sizeof(HANDLE) * (nCount + 1U));
DWORD status;
memcpy(handles, lpHandles, nCount * sizeof(HANDLE));
handles[nCount] = thread->event;
status = WaitForMultipleObjects(2, handles, FALSE, dwMilliseconds);
free(handles);
return status;
}

Resources