I have an app. which creates an HTTP service to listen to a few connections points we can use to check the app status.
That service runs in the background (with a go routine).
It gets initialized in the init() function among other things:
func init() {
...
initHttpEndPoints();
...
}
Can the fact that a go routine is created in the init() function cause issues when testing this app.?
I'm asking because it looks like my tests re-run the init() a second time and I'm wondering why that is and what the side effects could be... (probably not so good if all the go routines are all of a sudden duplicated.)
Note: The complete app. creates several hundred go routines in the init() function. I use the HTTP end point as an example.
Strongly related answer: Are tests run concurrently?
In addition to icza's answer, it sounds like you're using init() incorrectly with the testing package.
Rather than using init() to initialize things needed for tests, you should define the function TestMain().
Spec: Package initialization:
Package initialization—variable initialization and the invocation of init functions—happens in a single goroutine, sequentially, one package at a time. An init function may launch other goroutines, which can run concurrently with the initialization code. However, initialization always sequences the init functions: it will not invoke the next one until the previous one has returned.
There is nothing wrong about launching goroutines from init() functions, although you must remember that these goroutines run concurrently with the initialization process, so for example you can't assume anything about the initialization state of the (current) package.
If you see your init() functions running multiple times, that is most likely multiple tests run separately. init() functions run only once during the lifetime of a package.
Related
Currently, I am using usart_read_buffer_job function provided by ASF library. I placed this function inside the while(1) loop as below:
int main()
{
Some pieces of code for initialization;
while(1)
{
usart_read_buffer_job();
while(1) // The second infinite loop
{
Some other pieces of code;
}
}
}
It works perfectly well for the first interrupt handler call. However, after returning from the handler, I was no longer able to call the interrupt handler. The program kept running within the second infinite loop and was not able to execute usart_read_buffer_job() again. It was probably the cause of the handler 's malfunction.
In this case, my purpose is to jump into the USART interrupt handler regardless of the number of infinite loops being executed in main(). Of course, by not using ASF, the issue could be solved by manually set the handler but I still wonder how this issue could be solved by other functions provided by ASF.
Looking forward to getting the response from the community soon.
Thank you,
Thanks for very quick response.
The code which I am working on is confidentials. Hence, I could only share the ASF library functions with you and explain briefly how they work.
In the ASF, typically, we have two functions for handling the interrupt, namely usart_read_buffer_job and usart_read_job
Before using these two functions, the handler calls are defined by the two functions:
usart_register_callback: Registers a callback function, which is implemented by the user.
usart_enable_callback: The callback function will be called from the interrupt handler when the conditions for the callback type are met.
And these two functions above are placed in the initialization code as shown in the question.
Then, depending on the design purpose, handlers are called whenever a character or a group of characters are received via UART peripherals using usart_read_buffer_job/usart_read_job respectively.
usart_read_buffer_job: Sets up the driver to read from the USART to a given buffer. If registered and enabled, a callback function will be called.
usart_read_job: Sets up the driver to read data from the USART module to the data pointer given. If registered and enabled, a callback will be called when the receiving is completed.
You could find more details about these functions on http://asf.atmel.com/docs/latest/samd21/html/group__asfdoc__sam0__sercom__usart__group.html
In this case, assumming that the main program stalls due to some unexpected infinite loops, the handlers should still work at anytime after receiving command invoked from the UART peripherals and do some important tasks to solve out the problems, for example.
Hope that this explanation makes my previous question clearer. And, hope to get response from all of you soon.
First of all, do not put an infinite loop inside an infinite loop!!.
If you find yourself doing this, this indicates a probable design flow. Please revise your design.
(Let's call it the first rule)
Second, you seem to use event driven I/O (rather than polling) by registering a handler/callback.
Here is a second rule, you never call a handler yourself.
You register a callback function (handler) to be called when the event occurs.
If you are doing the initialization and configuration correctly, the code should work following this scheme:
void initialization()
{
/*Device and other initialization*/
...
usart_register_callback(...); /*Register usart_read_callback() here*/
usart_enable_callback(...);
}
int main()
{
initialization();
while(1)
{
/*Some other pieces of code*/
}
}
void usart_read_callback(...)
{
usart_write_buffer_job(...); /*Read data into your read data buffer*/
}
usart_read_buffer_job() will only invoke the callback one time, so after the callback has been dealt with, you must invoke usart_read_buffer_job() again (perhaps at the end of the callback if the processing is finished).
Only one infinite loop can run unless you have some kind of separate tasks (such as in FreeRTOS), each with their own loop.
My requirement is that a single frame of data is to be processed by two methods in parallel (they need to be parallel because they are which are computationally demanding).
Based on the result of either of the threads, the other need to be stopped.
That is if method 1 returns TRUE first, method 2 should be stopped.
If method 1 returns FALSE first, method 2 should not be stopped.
Similarly, if method 2 returns TRUE first, method 1 should be stopped.
If method 2 returns FALSE first, method 1 should not be stopped.
Please note that method 1 and method 2 are library calls (black box) and I don't have access to their internals. All I know is that they are computationally intense.
How can I implement it in C++/Windows? Any suggestions?
Take a look at the concurrency runtime.
Specifically the task namespace (http://msdn.microsoft.com/en-us/library/dd492427.aspx) and the when_any function (http://msdn.microsoft.com/en-us/library/hh749973.aspx).
concurrency::when_any will create a task that completes when any of the input tasks complete.
No matter if you use plain Windows threads, std::thread, Task Parallelism, or whatever library you prefer, you're still not going to achieve what you want given the details you provided in your question.
While you can certainly figure out when the first thread/task is finished (e.g. #j-w's answer), you cannot really stop the other task gracefully without telling your "blackbox library function" to stop (unless it provides a ways for explicit early cancellation). You didn't indicate the blackbox function can be told to cancel midway, so I'm assuming it is not.
You cannot simply kill the thread/task since this would create resource leaks and maybe even other nasty stuff such as dealocks, etc. depending on what your blackbox function does.
So, you could go with something like when_any, or other synchronization/signaling primitives, and just let the other thread/task continue to run even though you don't need the result, "un-blackbox" your library functions and add cancellation support, or forget about it altogether.
I'm trying to program my first COM Service EXE. And I'm can't to find some informations in the Net.
A Service EXE starts executing from its Run() method, do I need to implement my main functions in it to get my service works or do I need to implement a specific function that is related to it?
Thank you so much !!
You have not stated that you are using C++ and ATL, but it can be guessed from the tags given to the question.
If your COM objects do not need any global initialization, you do not have to modify the provided Run() function or anything similar. It works like this: If the service is not running, and some program requires a COM object from your service be created, the COM/DCOM infrastructure first starts the service. Alternatively, you can pre-start the service using any standard means (e.g. manually, or set its startup type to Automatic). Once the service is running, the COM objects are created within the service.
So, without a need for extra global initialization, you simply implement your COM objects as in any local server or in-process server. If they need any instance initialization, you will put it into the constructor of the COM object, or to its FinalConstruct method (this method gets called after the constructor, so you have take advantage of the fact that the object already exists, AND you can also fail it if needed, as FinalConstruct returns an HRESULT).
If you need a global (service-wide) initialization code, then you can put it into several places, each at different stage of the service construction. One of such places would be the Run() method, yes.
I have an multithreaded application that uses a DLL that I created. There is a certain function that will fail if the DLL has not run a certain function yet. How can I make sure that the thread that runs this application function waits for that DLL function to complete before continuing?
Visualization:
O = DLL Function Completes
T = Application Function Starts
App Thread:--------------O----------------------------------
DLL Thread:----------------------T--------------------------
Several approaches:
First thought would be to put the code into DLLMain(), which is executed automatically on application/DLL load. Not everything can be done here though, like blocking operations or operations that require loading other DLLs. Be sure to read and understand the docs if you try this approach.
The second thought is to throw or assert(), so that the init function must be called before any other one, like WSAStartup(). You would then have to call this once in main() before creating any other threads. This is a simple approach. It requires manual work and you can't create threads inside the ctors of globals (which is always dangerous anyway), but at least it will tell you if you got it wrong and, assuming the assert() approach, has zero overhead for release builds.
A third variant is using Boost.Thread's One-time Initialization initialization, which seems to do what you want.
You could use a named event.
Create an event for both the app and DLL to share first:
HANDLE myEvent = CreateEvent(NULL, false, false, L"MyEvent");
To signal complete use:
SetEvent(myEvent);
To wait for completion use:
WaitForSingleObject(myEvent, INFINITE);
In a unix pthreads based app I'm working on, I have objects of a particular class (call it class foo) being created in multiple threads. I need a specific public method of class foo invoked at or after 60s of the object coming into existence (it is not imperative that it happens at precisely 60s, just that it happens at either 60s or very shortly thereafter).
Any ideas on what timers are available that could I use to achieve this? Looking for either something that I could just drop right in to my class foo or which I could derive from.
The only real requirement is that it be thread-safe.
There are various platform specific mechanisms which will allow you to force an interruption of a thread at a given time, depending on various platform specific preconditions relating to the state of the thread. These are a bad idea unless you really need them and know why.
The correct solution, given the information in your question, would be to simply check elapsed time. Presumably these threads do some work in some sort of loop. As part of this loop, you should call e.g. foo::tick() and then let tick check to see if 60s has elapsed.
Rather than using timer, why not define a static member within the class that is incremented in the constructor (with proper protection of course)? When the static member reaches 60, either invoke the member or flag that the condition has occurred and invoke elsewhere.