I have a class which reads from a message queue. Now this class has also got a thread inside it. Depending on the type of the msg in msg q, it needs to execute different functions inside that thread as the main thread in class always keeps on waiting on msg q. As soon as it reads a message from queue, it checks its type and calls appropriate method to be executed in thread and then it goes back to reading again(reading in while loop).
I am using boost message q and boost threads
How can I do this.
Its something like this:
while(!quit) {
try
{
ptime now(boost::posix_time::microsec_clock::universal_time());
ptime timeout = now + milliseconds(100);
if (mq.timed_receive(&msg, sizeof(msg), recvd_size, priority, timeout))
{
switch(msg.type)
{
case collect:
{
// need to call collect method in thread
}
break;
case query:
{
// need to call query method in thread
}
break;
and so on.
Can it be done?
If it can be done, then what happens in the case when thread is say executing collect method and main thread gets a query message and wants to call it.
Thanks in advance.
Messages arriving while the receiving thread is executing long operations will be stored for later (in the queue, waiting to be processed).
If the thread is done with its operation, it will come back and call the receive function again, and immediately get the first of the messages that arrived while it was not looking and can process it.
If the main thread needs the result of the message processing operation, it will block until the worker thread is done and delivers the result.
Make sure you do not do anything inside the worker thread that in turn waits on the main thread's actions, otherwise there is the risk of a deadlock.
I'm creating 3 events with the following function:
HANDLE WINAPI CreateEvent(...);
I'm waiting on all (bWaitAll is set to TRUE) event objects or a timeout with:
DWORD WINAPI WaitForMultipleObjects(...);
The return value is:
WAIT_TIMEOUT
Is there an easy way to check each event to find the one(s) that was(where) not set?
As an example :
HANDLE evt1 = ....
HANDLE evt2 = ....
HANDLE evt3 = ....
HANDLE evts[3] = ....
DWORD ret = ::WaitForMultipleObjects(3, evts, TRUE, 10000);
After 10 sec :
'ret' is WAIT_TIMEOUT.
evt1 is set
evt2 is NOT set
evt3 is set
The return value tells me "The time-out interval elapsed and the conditions specified by the bWaitAll parameter are not satisfied.", but not which one were signaled and which one were not.
Thanks,
Yes, after WaitForMultipleObjects() returned call WaitForSingleObject() for each event specifying zero timeout.
It will return WAIT_TIMEOUT for events that are not signalled and WAIT_OBJECT_0 for signalled events. Don't forget to check for WAIT_FAILED.
Surely each event state might have been changed compared to the states they had at the moment WaitFormultipleObjects() returned.
OK. Total rewrite after having the question explained to me better in the comments.
So if I'm understanding this right now, you are calling WaitForMultipleObjects with bWaitAll set to true, and when you get WAIT_TIMEOUT back from it, want to figure out which objects are holding up the works.
In that case, I'm with sharptooth, sort of. You can call WaitForSingleObject with a 0 timeout for each object. The problem with doing this is that it has side-effects for some objects. For example, if you do this on a mutex and it succeeds, you not only know it wasn't the culprit, but you now own the mutex. If that isn't what you want, you'll have to know to immediately release it.
Any apporach you take is going to be subject to race conditions. Since you are outside of the "atomic" wait call, you could go through the process and discover that now they are all ready. You could get back a set of ready/unready that isn't what you actually had inside the wait call.
Ick.
None of this work, as WaitForSingleObject() will trigger an auto-reset event even when timeout is 0.
(Contrary to what MSDN says).
If your call returns WAIT_TIMEOUT it means that NONE of the objects you waited for was signalled..
cout<<"abcd";
sleep(100);
cout<<'\b';
If I want to print the string out and then get back one character ,
why a sleep() is needed here?
But when using printf in C ,it seems that it is not necessary, why?
char* a = "12345";
char* b = "67890";
threadA(){cout<<a;}
threadB(){cout<<b;}
beginthread (threadA);
sleep(100);
beginthread (threadB);
In the second pseudo code above ,is it right to use sleep()?
For calculating tomorrow date:
void get_tomorrow_date( struct timeval *date )
{
sleep( 86400 ); // 60 * 60 * 24
gettimeofday( date, 0 );
}
;)
There are two subtle issues that you need to understand:
Multi-threading
I/O and Buffering
I'll try to give you some idea:
Multi-threading and sleep
Having a sleep in a threaded environment makes sense. The sleep call makes you wait thereby giving the initial thread some scope to have completed its processing i.e. writing out the string abcd to the standard output before the other thread inserts the backspace character. If you didn't wait for the first thread to complete its processing, you'd have written the backspace character first, and then the string abcd and wouldn't notice any difference.
Buffered I/o
I/O typically happens in buffered, non-buffered and semi-buffered states. This can influence how long, if at all, you have to wait for the output to appear on the console.
Your implementation of cout is probably using a buffered model. Try adding a newline or the endl at the end of your cout statements to print a new line and have it flush immediately, or use cout << "abcd" << flush; to flush without printing a new line.
In the second case without the sleep there's a slim chance that the second thread could start working before the first, resulting in the output "6789012345".
However a "sleep" isn't really the way to handle synchronisation between threads. You'd normally use a semaphore or similar in threadA() which threadB() has to wait for before doing its work.
The reason that the call to sleep makes your code work is because you are using it to turn the potentially parallel execution of the two output stream actions into a single, sequential action. The call to sleep() will allow the scheduler to switch away from the main thread of execution and execute thread A.
If you don't put sleep() in, the order of thread execution is not guaranteed and thread B could well start executing/printing before thread A had a chance to do that.
I think you need to understand what sleep does in general, and understand why it might exist.
sleep does what it sounds like. It instructs the OS to put the requesting task (where a task is a thread of execution) to sleep by removing it from the list of currently running processes and putting it on some sort of wait queue.
Note that there are also times when the OS will put you to sleep whether you like it or not. An example would be any form of blocking I/O, like reading a file from disk. The OS does this so that other tasks may get the CPU's attention while you're off waiting for your data.
One would use sleep voluntarily for similar purposes that the OS would. For example, if you have multiple threads and they're waiting on the completion of some computation, you'll probably want to voluntarily relinquish the CPU so that the computation can complete. You may also voluntarily relinquish the CPU so that other threads have a chance to run. For example, if you have a tight loop that's highly CPU-bound, you'll want to sleep now and then to give other threads a chance to run.
What it looks like you're doing is sleeping for the sake of something being flushed to stdout so that some other thread won't write to stdout before you. This, however, isn't guaranteed to work. It might work incidentally, but it's certainly not what you'd want to do by design. You'd either want to explicitly flush your buffer and not sleep at all, or use some form of synchronization.
As for why printf doesn't exhibit those issues... well, it's a crapshoot. Both printf and cout use some form of buffered output, but the implementation of each may be different.
In summary, it's probably best to remember the following:
When you want to synchronize, use synchronization primitives.
When you want to give someone else a chance to run, sleep.
The OS is better at deciding whether an I/O operation is blocking or not.
if you're having problems seeing the "abcd" being printed, it's because you're not giving cout an endline character to flush the buffer.
if you put
cout << "abcd" << endl;
you would be able to see the characters, then it would beep. no sleep necessary.
while( true )
{
msgStack.Lock();
process( msgStack.pop_msg());
msgStack.Unlock();
sleep(0);
}
sleep in the first example is just to print message a little before you will see "backspace" action. In the second example sleep "can" help. But it is weird. You won't be able to synchronize console outs with sleep in some more complex case.
In the code that launches two threads:
beginthread (threadA);
sleep(100);
beginthread (threadB);
the sleep() waits for 100 ms and then continues. The programmer probably did this in order to give threadA a chance to start up before launching threadB. If you must wait for threadA to be initialized and running before starting threadB, then you need a mechanism that waits for threadA to start, but this is the wrong way to do it.
100 is a magic cookie, chosen arbitrarily, probably accompanying a thought like "it should never take threadA more than 100 ms to start up." Assumptions like this are faulty because you have no way of knowing how long it will take for threadA to start. If the machine is busy or if the implementation of threadA changes it could easily take longer than 100 ms for the thread to launch, run its startup code, and get to it's main loop (if it is that kind of thread).
Instead of sleeping for some arbitrary amount of time, threadA needs to tell the main thread when it is up & running. One common way of doing this is by signaling an event.
Sample code that illustrates how to do this:
#include "stdafx.h"
#include <windows.h>
#include <process.h>
struct ThreadParam
{
HANDLE running_;
HANDLE die_;
};
DWORD WINAPI threadA(void* pv)
{
ThreadParam* param = reinterpret_cast<ThreadParam*>(pv);
if( !param )
return 1;
// do some initialization
// : :
SetEvent(param->running_);
WaitForSingleObject(param->die_, INFINITE);
return 0;
}
DWORD WINAPI threadB(void* pv)
{
ThreadParam* param = reinterpret_cast<ThreadParam*>(pv);
if( !param )
return 1;
// do some initialization
// : :
SetEvent(param->running_);
WaitForSingleObject(param->die_, INFINITE);
return 0;
}
int main(int argc, char** argv)
{
ThreadParam
paramA = {CreateEvent(0, 1, 0, 0), CreateEvent(0, 1, 0, 0) },
paramB = {CreateEvent(0, 1, 0, 0), CreateEvent(0, 1, 0, 0) };
DWORD idA = 0, idB = 0;
// start thread A, wait for it to initialize
HANDLE a = CreateThread(0, 0, threadA, (void*)¶mA, 0, &idA);
WaitForSingleObject(paramA.running_, INFINITE);
// start thread B, wait for it to initi
HANDLE b = CreateThread(0, 0, threadB, (void*)¶mB, 0, &idB);
WaitForSingleObject(paramB.running_, INFINITE);
// tell both threads to die
SetEvent(paramA.die_);
SetEvent(paramB.die_);
CloseHandle(a);
CloseHandle(b);
return 0;
}
It's not needed - what output do you get if you omit it?
The only thing sleep does is pauses execution on the calling thread for the specified number of milliseconds. It in no way will affect the outcome of any printing you might do.
Sleep can be used to avoid a certain thread/process (yeah, i know they are different things) hogging the processor.
On the other hand, printf is thread safe. Cout is not. That may explain differences in their behaviour.
EDIT: I have now edited my code a bit to have a rough idea of "all" the code. Maybe this
might be helpful to identify the problem ;)
I have integrated the following simple code fragement which either cancels the timer if data
is read from the TCP socket or otherwise it cancels the data read from the socket
// file tcp.cpp
void CheckTCPSocket()
{
TRequestStatus iStatus;
TSockXfrLength len;
int timeout = 1000;
RTimer timer;
TRequestStatus timerstatus;
TPtr8 buff;
iSocket.RecvOneOrMore( buff, 0, iStatus, len );
timer.CreateLocal();
timer.After(timerstatus, timeout);
// Wait for two requests – if timer completes first, we have a
// timeout.
User::WaitForRequest(iStatus, timerstatus);
if(timerstatus.Int() != KRequestPending)
{
iSocket.CancelRead();
}
else
{
timer.Cancel();
}
timer.Close();
}
// file main.cpp
void TestActiveObject::RunL()
{
TUint Data;
MQueue.ReceiveBlocking(Data);
CheckTCPSocket();
SetActive();
}
This part is executed within active Object and since integrating the code piece above I always get the kernel panic:
E32User-CBase 46: This panic is raised by an active scheduler, a CActiveScheduler. It is caused by a stray signal.
I never had any problem with my code until now this piece of code is executed; code executes fine as data is read from the socket and
then the timer is canceled and closed. I do not understand how the timer object has here any influence on the AO.
Would be great if someone could point me to the right direction.
Thanks
This could be a problem with another active object completing (not one of these two), or SetActive() not being called. See Forum Nokia. Hard to say without seeing all your code!
BTW User::WaitForRequest() is nearly always a bad idea. See why here.
Never mix active objects and User::WaitForRequest().
(Well, almost never. When you know exactly what you are doing it can be ok, but the code you posted suggests you still have some learning to do.)
You get the stray signal panic when the thread request semaphore is signalled with RThread::RequestComplete() by the asynchronous service provider and the active scheduler that was waiting on the semaphore with User::WaitForAnyRequest() tries to look for an active object that was completed so that its RunL() could be called, but cannot find any in its list of active objects.
In this case you have two ongoing requests, neither of which is controlled by the active scheduler (for example, not using CActive::iStatus as the TRequestStatus; issuing SetActive() on an object where CActive::iStatus is not involved in an async request is another error in your code but not the reason for stray signal). You wait for either one of them to complete with WaitForRequest() but don't wait for the other to complete at all. The other request's completion signal will go to the active scheduler's WaitForAnyRequest(), resulting in stray signal. If you cancel a request, you will still need to wait on the thread request semaphore.
The best solution is to make the timeout timer an active object as well. Have a look at the CTimer class.
Another solution is just to add another WaitForRequest on the request not yet completed.
You are calling TestActiveObject::SetActive() but there is no call to any method that sets TestActiveObject::iStatus to KRequestPending. This will create the stray signal panic.
The only iStatus variable in your code is local to the CheckTCPSocket() method.
I am working on writing a wrapper DLL to interface a communication DLL for a yokogawa WT1600 power meter, to a PC based automation package. I got the communication part to work but I need to thread it so that a 50ms scan time of the automation package can be maintained. (The Extended Function Block (EFB) Call will block the scan until it returns)
These are the steps I need to do.
Call EFB
EFB creates a thread to perform communication setup (takes about 200ms to do)
EFB returns EFB_BUSY while the thread is doing the work
3a. (automation program continues scanning until it comes back to the EFB call)
Call EFB passing in that it returned busy on the last call
EFB checks if the thread has returned
If the thread returned Then the EFB returns success, Else return EFB_BUSY
repeat 3a-6 until efb returns success
So my problem is, how do I create a thread that exists past the life of the function that called it? And how do I get that thread return value when I call back into the DLL?
EDIT #1
HeavyFunction::HeavyFunction^ hf; //HeavyFunction is a class that has a time consuming function in it
ThreadStart^ efbThreadDelegate;
Thread^ efbThread;
if( pEfbData->nBlockingRecall != DOEFB_BUSY ) {
hf = gcnew HeavyFunction::HeavyFunction;
hf->iiStart = (int)(pEfbData->uParams[0].dw);
hf->iiEnd = (int)(pEfbData->uParams[1].dw);
efbThreadDelegate = gcnew ThreadStart( hf, &HeavyFunction::HeavyFunction::iGetPrime );
efbThread = gcnew Thread( efbThreadDelegate );
efbThread->Start();
return DOEFB_BUSY;
}else if ( efbThread->IsAlive ) {
return DOEFB_BUSY;
}else {
uRetValue->dw = hf->iReturn;
return 0;
}
Will efbThread still have the same thread handle upon a subsequent call?
EDIT #2
I got it to work by creating a global HANDLE for a Mutex and a thread. Initializing the mutex in the init entry point (done upon dll loading) and creating the thread in the main function when a call is actually made to the dll.
I used the sample code from MSDN: Creating Threads as my model.
Any thread created (whether in a DLL or elsewhere) will not stop spontaneously. In particular, the function that created the thread may return. The new thread would still run even if the creator thread exited. That is, assuming it didn't hit the end of its entry function.
Windows threads return a DWORD when ready. To peek, call WaitForSingleObject on the thread handle with a 0 second timeout, and it that succeeds, call GetExitCodeThread .
I don't understand your whole "EFB" thing, neither what it is nor what it does, though. If it is doing funny things to normal Windows threads, all bets are off.