i have a threadProc
void* ThreadProc(void* xyz)
{
//do some work..
}
now from the main thread.. i call this thread and do not wish to wait for it to finish
WaitForSingleObject(hThread, 0)
now my flow of program is succh that the case may arrive where
first call to thread is not finished and 2nd time same ThreadProc() is called.
So ...
1. How does OS handles this scenario? Will this kind of program give unexpected results?
2. If this is wrong way of doing it, what is the correct way?
Because ultimately I want one function to be called asynchronously, may be running multiple instances at the same time.
Every thread has a separate stack, so as long as all variables in the thread callback function are local, there are no conflicts. But if you would access variables that are global/static, then they are shared between all threads and all access to them needs to be handled carefully. Use mutex/semaphores/critical sections for such. The same goes for calling library functions which you don't know are thread-safe.
Will this kind of program give unexpected results?
That depends entirely on the body of the thread callback function. You should however wait using WaitForSingleObject(hThread, INFINITE). Right now you wait 0ms, which does nothing.
Related
I am working on raspberry pi camera module interface, and it involves a callback function which you register to the mmal buffer, and it is run each time a frame is grabbed.
My confusion emerges in the case where another frames arrive when the previously running callback function did not finish in time.
Let's imagine we give some loop a callback function, which will be run when a certain event happens. If the callback function that was called with the previous happening of that event, did not yet finish its job, what will happen when the next event arrives? Can same callback function start running (like another thread?) while the previous one is still running?
I doubt it would, but I had to ask to understand.
It depends on the implementation of the software wich is calling your callback.
The most probable is that it will not launch a thread each time a frame is received and wait the return of the callback before waiting the next frame.
You have too look into the mmal buffer documenattion (and/or codeĆ to understand how it works and if you need to have thread safe code in your callback.
It could be implemented in different ways.
It could be the case that the frames are stored in a buffer and the function is called on them one after another. This seems to be somewhat like a bounded buffer producer-consumer. Maybe the callback function is a realtime function (they have strict runtime guarantees which ensure the buffer does not overflow) in this case?
Or the function is spawned in a separate thread for each frame. If it's calling the function simultaneously in separate threads, the callback function should be thread-safe.
http://en.wikipedia.org/wiki/Thread-safety
my main program (all c code) starts a server function as a separate thread (pthread_create).
This function waits for incoming input and does certain things with it. Meanwhile the main program keeps doing things as well (the main program does not wait for the server function to finish its job before it continues).
Now there is the chance that an error occurs in the server function (socket problem, ...). The server function then returns a certain value (for example "-1").
If that is the case I want to abort the execution of the whole program.
How can I handle this?
My only idea is to start a second thread that constantly verifies a global variable that the server thread changes in case of an error. Then the second thread handles the program abortion.
What other options do I have?
Kind regards
You can use pthread_join to wait for termination of the child thread in the parent thread.
Or pthread_cond_wait to implement a similar stuff.
gcc 4.4.3 c89
I have a event loop that runs in a separate thread.
My design is like this below, just sample code to help explain.
I need to somehow wait for the initialization to complete before I can make a call to the get_device_params.
I did put a usleep for 3 seconds just before the call to the get_device_params, but I don't really want to block.
Many thanks for any suggestions,
void* process_events(void *data)
{
switch(event_type)
{
case EVT_INITIALIZED:
/* Device is now initialized */
break;
}
}
int main(void)
{
/* Create and start thread and process incoming events */
process_events();
/* Initialize device */
initialize_device();
/* Get device parameters */
/* However, I cannot run this code until initialization is complete */
get_device_params();
return 0;
}
If this separate thread is a POSIX thread (i.e. you're on a typical UNIX platform), then you can use pthread conditional variables.
You call pthread_cond_wait() in the waiting thread. When the init thread finishes its work, you call pthread_cond_signal(). In my opinion that's a canonical way to wait for initialization in another thread.
I need to somehow wait for the initialization to complete before I can make a call to the get_device_params.
Since you apparently have some sort of a FSM inside the process_events(), and it why ever runs in a separate thread, you shouldn't do anything from the main thread with the device.
In other words, logically, call to the get_device_params(); should be placed inside the FSM, on the event that the device is initialized EVT_INITIALIZED which I presume is triggered by the initialize_device().
Alternatively, you can create second FSM (possibly in another thread) and let the process_events() (the first FSM) after it has finished its own processing, forward the EVT_INITIALIZED event to the second FSM. (Or initialize_device() could send the event to the both FSMs simultaneously.)
To me it seems (from the scarce code you have posted) that your problem is that you try to mix sequential code with an event based one. Rule of thumb: in event/FSM based application all code should run inside the FSM, being triggered by an event; there should be no code which may run on its own outside of the FSM.
If it were me, I would probably use a barrier. In main you can call pthread_barrier_init, indicating that you have 2 threads. Then, in main call pthread_barrier_wait, to wait on the barrier you initialized, after calling your device initialization function. Finally, in the device thread, after you initialize your device, you can call pthread_barrier_wait on the same barrier and when both threads are waiting, the barrier will have been satisfied, so both threads will continue. I find barriers easier to use than condition variables sometime, but I'm sure that's an issue of preference.
I am supposed to implement a userlevel threads library in C. To do so, I need to implement yield(), createThread() and destroyThread() functions. I believe I've got the basics right:
To keep track of threads, I'll use a queue of ThreadControlBlock elements (which resemble PCBs in an OS) that look like this:
struct ThreadControlBlock {
int ThreadId,
u_context *context };
We can use the setcontext() family of functions to "save" and "load" the context.
Upon initialization of the program, initialize ThreadQueue with no elements.
Now the part I am not getting: when a thread calls yield(), I get the current context and save it in a ThreadControlBlock and put in the queue. Then get the first element in the queue and load the context in it, and execution proceeds.
The question is, if I do this, say I am a thread calling yield() and the next thread is myself. If I am saving the context and loading it again, upon re-entering wouldn't I be at the exact same spot where I was (before calling yield()?) And this would keep going on forever?
When a thread calls yield(), you have to save the state of a thread that's about to return from a yield() call. Don't save the context from immediately before the yield().
The same issue actually applies if you're switching to another task, too - since that other task saved its context at the same point (where it was about to switch to a second task). Using setcontext() and getcontext(), you need to use a static variable to keep track of whether you're switching in or switching out:
static volatile int switched;
switched = 0;
getcontext(current->context);
if (!switched)
{
switched = 1;
setcontext(next->context);
}
Alternatively, you can just use swapcontext(current->context, next->context);
It's perfectly reasonable in your yield() implementation to check to see if the next thread is the current thread and treat that case as a no-op.
If there are no other threads to run besides the current thread then there is nothing else to do besides just return from yield. I wouldn't bother with calling swapcontext in this case, though -- just detect and return.
I think that what you are actually dealing with is what to do when no threads (including the current one) when yield is called. An easy way to deal with this is to have an idle thread, which is only run when the run queue (ready threads) is empty. This thread will probably just:
{
while (1) {
yield();
pause();
}
}
This allows your program to go to sleep (via pause) until a signal happens. Hopefully the signal will be some event that makes one of the other threads ready to run, so the next call to yield will run the other thread instead of running the idle thread again.
OK, I'm a bit confused here. The following code works:
HANDLE CreateSideThread()
{
DWORD dwGenericThread;
HANDLE hThread1 = CreateThread(NULL, 0, CallBackFunc, NULL, 0, &dwGenericThread);
return hThread1;
}
int main()
{
HANDLE Thread1;
Thread1 = CreateSideThread();
WaitForSingleObject(hThread1, INFINITE);
SomeOtherFunction();
return 0;
}
The program does other things but you get the idea. It basically creates a new thread and executes whatever it is in CallBackFunc (which is an endless loop that check db status).
Now, if I remove WaitForSingleObject() then the program will not even try CallBackFunc once and execute SomeOtherFunction().
What's the point then of a thread? I mean, i'm confused here.
What I am trying to do is call that thread with the check for the database status and keep that thread going while I continue with my program, calling other functions.
What am I doing wrong?
Please post a sample snippet.
Thanks
Without the WaitForSingleObject, your call to SomeOtherFunction() probably returns quickly enough for the program to exit before the new thread even gets a chance to run once.
When a C program returns from its main() function, the runtime system calls exit() for you. This forcibly exits your program even if other threads are trying to run at the same time. This is in contrast to other languages like Java for example, where exiting the main thread will not exit the process until all other (non-daemon) threads have finished running too.
Threads are typically used for doing background work and freeing up the calling thread to do other things.
Normally, the behavior you describe (calling SomeOtherFunction()) is exactly what you'd want: I am going to kick of a background 'job' and go about my life.
It would appear that your example is just fine - though if you merely return from main() your thread will of course terminate (as it's owned by the parent process).
Maybe some more detail on why what you're doing isn't what you expect to happen?
What you're finding is that the main thread completes before you notice CallbackFunc is called. When you have the Wait call in, the main thread is blocked until the new thread finishes and so you see the thread func being executed.
Threads are not as cheap as you think, if you replace the SomeOtherFunction with something that takes a long enough time to run, you'll see your thread function being called even without the Wait call.
CallBackFunc will of course be called, but there is no guarantee, when your stared threads will be up and running. They will be working once, but its unpredictable when the start doing so. Thats the job and property of the systems scheduler. In your case they do not anything when the second function is already called.