c++ winapi threads - c++

These days I'm trying to learn more things about threads in windows. I thought about making this practical application:
Let's say there are several threads started when a button "Start" is pressed. Assume these threads are intensive (they keep running / have always something to work on).
This app would also have a "Stop" button. When this button is pressed all the threads should close in a nice way: free resources and abandon work and return the state they were before the "Start" button was pressed.
Another request of the app is that the functions runned by the threads shouldn't contain any instruction checking if the "Stop" button was pressed. The function running in the thread shouldn't care about the stop button.
Language: C++
OS: Windows
Problems:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
How should I construct the wrapper function so that I can stop the thread properly?
( without using TerminateThread or some other functions )
What if the programmer allocates some memory dynamically? How can I free it before closing
the thread?( note that when I press "Stop button" the thread is still processing data)
I though about overloading the new operator or just imposing the usage of a predefined
function to be used when allocating memory dynamically. This, however, means
that the programmer who uses this api is constrained and it's not what I want.
Thank you
Edit: Skeleton to describe the functionality I'd like to achieve.
struct wrapper_data
{
void* (*function)(LPVOID);
LPVOID *params;
};
/*
this function should make sure that the threads stop properly
( free memory allocated dynamically etc )
*/
void* WrapperFunc(LPVOID *arg)
{
wrapper_data *data = (wrapper_data*) arg;
// what to write here ?
// if i write this:
data->function(data->params);
// i cannot stop the function from executing
delete data;
}
// will have exactly the same arguments as CreateThread
MyCreateThread(..., function, params, ...)
{
// this should create a thread that runs the wrapper function
wrapper_data *data = new wrapper_data;
data->function = function;
data->params = params;
CreateThread(..., WrapperFunc, (LPVOID) wrapper_data, ...);
}
thread_function(LPVOID *data)
{
while(1)
{
//do stuff
}
}
// as you can see I want it to be completely invisible
// to the programmer who uses this
MyCreateThread(..., thread_function, (LPVOID) params,...);

One solution is to have some kind of signal that tells the threads to stop working. Often this can be a global boolean variable that is normally false but when set to true it tells the threads to stop. As for the cleaning up, do it when the threads main loop is done before returning from the thread.
I.e. something like this:
volatile bool gStopThreads = false; // Defaults to false, threads should not stop
void thread_function()
{
while (!gStopThreads)
{
// Do some stuff
}
// All processing done, clean up after my self here
}
As for the cleaning up bit, if you keep the data inside a struct or a class, you can forcibly kill them from outside the threads and just either delete the instances if you allocated them dynamically or let the system handle it if created e.g. on the stack or as global objects. Of course, all data your thread allocates (including files, sockets etc.) must be placed in this structure or class.
A way of keeping the stopping functionality in the wrapper, is to have the actual main loop in the wrapper, together with the check for the stop-signal. Then in the main loop just call a doStuff-like function that does the actual processing. However, if it contains operations that might take time, you end up with the first problem again.

See my answer to this similar question:
How do I guarantee fast shutdown of my win32 app?
Basically, you can use QueueUserAPC to queue a proc which throws an exception. The exception should bubble all the way up to a 'catch' in your thread proc.
As long as any libraries you're using are reasonably exception-aware and use RAII, this works remarkably well. I haven't successfully got this working with boost::threads however, as it's doesn't put suspended threads into an alertable wait state, so QueueUserAPC can't wake them.

If you don't want the "programmer" of the function that the thread will execute deal with the "stop" event, make the thread execute a function of "you" that deals with the "stop" event and when that event isn't signaled executes the "programmer" function...
In other words the "while(!event)" will be in a function that calls the "job" function.
Code Sample.
typedef void (*JobFunction)(LPVOID params); // The prototype of the function to execute inside the thread
struct structFunctionParams
{
int iCounter;
structFunctionParams()
{
iCounter = 0;
}
};
struct structJobParams
{
bool bStop;
JobFunction pFunction;
LPVOID pFunctionParams;
structJobParams()
{
bStop = false;
pFunction = NULL;
pFunctionParams = NULL;
}
};
DWORD WINAPI ThreadProcessJob(IN LPVOID pParams)
{
structJobParams* pJobParams = (structJobParams*)pParams;
while(!pJobParams->bStop)
{
// Execute the "programmer" function
pJobParams->pFunction(pJobParams->pFunctionParams);
}
return 0;
}
void ThreadFunction(LPVOID pParams)
{
// Do Something....
((structFunctionParams*)pParams)->iCounter ++;
}
int _tmain(int argc, _TCHAR* argv[])
{
structFunctionParams stFunctionParams;
structJobParams stJobParams;
stJobParams.pFunction = &ThreadFunction;
stJobParams.pFunctionParams = &stFunctionParams;
DWORD dwIdThread = 0;
HANDLE hThread = CreateThread(
NULL,
0,
ThreadProcessJob,
(LPVOID) &stJobParams, 0, &dwIdThread);
if(hThread)
{
// Give it 5 seconds to work
Sleep(5000);
stJobParams.bStop = true; // Signal to Stop
WaitForSingleObject(hThread, INFINITE); // Wait to finish
CloseHandle(hThread);
}
}

Related

How to use Thread to run a class Constructor

Is there a way to construct a class with specific parameters in a separate thread?
In the examples I have seen I can only see thread running functions and member functions. To be more specific, I would need it to run this constructor in a separate thread:
Thermistor(ukd_Adc * pAdc,
const lookup_table_t * pLUT,
uint8_t numOfLutElements);
I want to construct the class in a different thread to assert functionality and check for edge cases.
If there is an edge case like the pointer to ukd_Adc being NULL, the assert will make it hang in an infinite loop. This thread will allow me to set a time limit on how long the constructor may run so it does not go into an infinite loop.
This is for testing purposes since google test does not have a timeout feature to my knowledge.
If you simply want to construct an object on a separate thread and check if it has successfully finished within a specific time constrain, use:
int main() {
std::promise<std::shared_ptr<Thermistor>> promise;
std::future<std::shared_ptr<Thermistor>> future = promise.get_future();
std::thread([&promise](ukd_Adc * pAdc,
const lookup_table_t * pLUT,
uint8_t numOfLutElements) {
promise.set_value_at_thread_exit(std::make_shared<Thermistor>(pAdc, pLUT, numOfLutElements));
}, <pAdc-value>, <pLUT-value>, <numOfLutElements-value>).detach();
auto status = future.wait_for(std::chrono::seconds(3));
if (status == std::future_status::ready)
{
// succeeded
}
else
{
// failed
}
}
You can use the alarm() function to raise a signal (SIGALRM) after a specified amount of time:
static bool alarmed = false;
extern "C" void handler(int signo)
{
alarmed = true;
}
signal(SIGALRM, handler);
alarm(5); // seconds to SIGALRM
// do stuff
// if (alarmed) ...
You could use pthreads start the process and when you don't like your thread anymore you can kill it off with pthread_cancel
pseudo code
start thread
wait
cancel thread if not finished

c++ implementing semaphore on my own

let's pretend there are no libraries that provide semaphores for C++. I wrote this:
#include <vector>
#include <Windows.h>
class Semaphore {
HANDLE mutexS; // provides mutex in semaphore rutines
std::vector<HANDLE> queue; // provides FIFO queue for blocked threads
int value; // semaphore's value
public:
Semaphore(int init=1);
~Semaphore();
void wait();
void signal();
};
Semaphore::Semaphore(int init) {
value = init;
queue = std::vector<HANDLE>();
mutexS = CreateMutex(0,0,0);
}
Semaphore::~Semaphore() {
CloseHandle(mutexS);
}
void Semaphore::signal() {
WaitForSingleObject(mutexS, INFINITE);
if (++value <= 0) {
HANDLE someOldThread = queue.front();
ResumeThread(someOldThread);
queue.erase(queue.begin());
CloseHandle(someOldThread);
}
ReleaseMutex(mutexS);
}
I would like to know why this implementation of wait() doesn't work:
void Semaphore::wait() {
WaitForSingleObject(mutexS, INFINITE);
if (--value < 0) {
HANDLE thisThread = GetCurrentThread();
queue.push_back(thisThread);
ReleaseMutex(mutexS);
SuspendThread(thisThread );
}
else
ReleaseMutex(mutexS);
}
And this one works:
void Semaphore::wait() {
WaitForSingleObject(mutexS, INFINITE);
if (--value < 0) {
HANDLE thisThread = GetCurrentThread();
HANDLE alsoThisThread;
DuplicateHandle(GetCurrentProcess(), thisThread, GetCurrentProcess(), &alsoThisThread, 0, 0, DUPLICATE_SAME_ACCESS);
queue.push_back(alsoThisThread);
ReleaseMutex(mutexS);
SuspendThread(alsoThisThread);
}
else
ReleaseMutex(mutexS);
}
What exactly happens in each case? I've been banging my head over it for a lot of time now. The first implementation of wait, which doesn't work, makes my program block (well, it probably blocks some thread forever). The 2nd implementation works like a charm. What gives ? Why do I need to duplicate thread handles and block the duplicate ?
MSDN helps a lot here ;)
GetCurrentThread returns a pseudo-handle which is a constant for "the current thread":
A pseudo handle is a special constant that is interpreted as the current thread handle.
So when you push it in the queue, you are always pushing a constant that says "the current thread", which is obviously not what you want.
To get a real handle, you have to use DuplicateHandle
If hSourceHandle is a pseudo handle returned by GetCurrentProcess or GetCurrentThread, DuplicateHandle converts it to a real handle to a process or thread, respectively.
A final note: I suppose you are implementing this as a "test" right? Because there are several potential problems.. A very good learning exercise would be to dig them out. But you should not use this in production code.
Out of curiosity: if you want to experiment a little more, the "canonical" way of implementing semaphore with mutexes is to use two mutexes: see here
MSDN documentation for GetCurrentThread has the answer (accents are mine):
The return value is a pseudo handle for the current thread.
A pseudo handle is a special constant that is interpreted as the current thread handle. The calling thread can use this handle to specify itself whenever a thread handle is required.
...
The function cannot be used by one thread to create a handle that can be used by other threads to refer to the first thread. The handle is always interpreted as referring to the thread that is using it. A thread can create a "real" handle to itself that can be used by other threads, or inherited by other processes, by specifying the pseudo handle as the source handle in a call to the DuplicateHandle function.

notify thread about changes in variable (signals?)

I have main() and thread in the same program.
there is a variable named "status", that can get several values
I need that when the variable changes, to notify the thread (the thread cnat wait for the status variable, it is already doing fluent task) .
is there an easy way to do so? similar to interrupts? how about signals?
the function inside the main:
int main()
{
char *status;
...
...
while (1)
{
switch (status)
{
case: status1 ...notify the thread
case: status2 ...notify the thread
case: status3 ...notify the thread
}
}
}
if someone could give me an example it will be great!
thanks!
Since you're already using the pthread library you can use conditional variables to tell the thread that there is data ready for processing. Take a look at this StackOverflow question for more information.
I understand that you do not want to wait indefinitely for this notification, however C++ only implements cooperative scheduling. You cannot just pause a thread, fiddle with its memory, and resume it.
Therefore, the first thing you have to understand is that the thread which has to process the signal/action you want to send must be willing to do so; which in other words means must explicitly check for the signal at some point.
There are multiple ways for a thread to check for a signal:
condition variable: they require waiting for the signal (which might be undesirable) but that wait can be bounded by a duration
action queue (aka channel): you create a queue of signals/actions and every so often the target thread checks for something to do; if there is nothing it just goes on doing whatever it has to do, if there is something you have to decide whether it should do everything or only process the N firsts. Beware of overflowing the queue.
just check the status variable directly every so often, it does not tell you how many times it changed (unless it keeps an history: but then we are back to the queue), but it allows you to amend your ways.
Given your requirements, I would think that the queue is probably the best idea among those three.
Might be this example helpful for you.
DWORD sampleThread( LPVOID argument );
int main()
{
bool defValue = false;
bool* status = &defValue;
CreateThread(NULL, 0, sampleThread, status, 0,NULL);
while(1)
{
//.............
defValue = true; //trigger thread
// ...
}
return 0;
}
DWORD sampleThread( LPVOID argument )
{
bool* syncPtr = reinterpret_cast<bool*>(argument);
while (1)
{
if (false == *syncPtr)
{
// do something
}
else (true = *syncPtr)
{
//do somthing else
}
}
}

How to notify outside thread of main thread state without using global variables?

Say i have main thread and it is running my win32 procedure and a few worker threads to carry out functions that are clicked on by the user.
Lets say there is a change in the main function (I want 1 button to be available while another one is not, but only when the program enters a certain state (i.e by a boolean trigger or something of that nature), and notify all running threads that i want to disable to terminate?)?
Passing arguments to the thread only captures the state of the main thread at a certain point in time. What if i want to monitor the state of my main thread across different time frames or events?
I currently have a few global boolean values to flag/signal the program's current mode or state and that is how i notify the worker threads in how they should change their behavior.
Should I eliminate my use of global variables or keep them? Or if i should eliminate the global varialbes, how would i reimplement my program?
You can still pass arguments to your worker thread at construction time. But do not pass it copies of your state variables (because as you said, they "only captures the state of the main thread at a certain point in time", which is the worker thread creation time).
Instead, pass it pointers (or references) to your state variables.
Because they are pointers, your worker thread will have access to the latest data from the main thread without the need to use globals.
Below is a pseudo-code example (without any synchronization mechanism, like mutex):
DWORD MyThreadFunction( LPVOID argument );
int main()
{
bool mySyncVar = false;
bool* mySyncVarPtr = &mySyncVar;
CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
mySyncVarPtr, // argument to thread function--NOTE THAT THIS IS
// A POINTER TO THE SYNC VARIABLE
0, // use default creation flags
NULL); // returns the thread identifier
for (...)
{
// Do stuffs
mySyncVar = true; // Will trigger worker thread
// ...
}
return 0;
}
DWORD MyThreadFunction( LPVOID argument )
{
bool* syncPtr = reinterpret_cast<bool*>(argument); // Remember this
// is a pointer
for (...)
{
while (false == *syncPtr)
{
// Wait...
}
// Trigger
// Update your buttons now
}
}

A kind of thread pool

I used to call CreateThread() for all my threads, and WaitForMultipleObjects(), an leave the routine.
To get somewhat faster code, I'd like to do a kind of thread pool. My thread pools are sometimes created, later used multiple times, and later destroyed (ie., there is not a single pool created at the begining of the program). Each thread in my thread pool call the same routine with different parameters, the number of threads is constant, and they always need to be launched at the same time.
What I do is as follows :
DWORD WINAPI runFunction(LPVOID p) {
Thread* = (Thread*) p;
while(true) {
WaitForSingleObject(thread->awakeEvenHandle, INFINITE);
thread->run();
SetEvent(thread->SleepingEventHandle);
SuspendThread(thread->handle);
}
return 0;
}
void ExecuteThreads(std::vector<Thread*> &threads) {
HANDLE* waitingEvents = new HANDLE[threads.size()];
for (int i=0; i<threads.size(); i++) {
if (threads[i]->handle == NULL) {
threads[i]->AwakeEventHandle = CreateEvent(NULL, true, false, "Awake");
threads[i]->SleepingEventHandle = CreateEvent(NULL, true, false, "Sleeping");
threads[i]->handle = CreateThread(NULL, 0. runFunction, (void*) threads[i], CREATE_SUSPENDED, NULL);
}
ResumeThread(threads[i]->handle);
ResetEvent(threads[i]->SleepingEventHandle);
SetEvent(threads[i]->AwakeEventHandle);
waitingEvents[i] = threads[i]->SleepingEventHandle;
}
WaitForMultipleObjects( threads.size(), waitingEvents, TRUE, INFINITE);
}
My class Thread has a destructor which calls CloseHandle for the HANDLEs SleepingEventHandle and AwakeEventHandle, and for the thread handle. The function Thread::run() is pure virtual, and it's up to the coder to inherit the Thread for an actual run() implementation.
As it, the code doesn't work . One reason is that when I don't need this pool anymore, the destructors of the Threads are called, but the runFunction cannot exits and this crashes (the pointer "thread" has been destroyed but is still used the the function). There are probably many other problems with my code.
How would you do it, in a simple manner ? Is-there an easy fix ? What problems will I encounter with this code ?
Thanks!
Why do you have to deal with such low level api functions? Have a look at boost::thread and boost::thread_group. Also there is a thread pool implementation works with boost::thread.
Now if your threads work for a short period of time, your system will have remarkable overhead with creating and signaling all those threads and events. ppl Task Parallelism or tbb::task are definitely the ways to go.