libuv - how to stop tcp server, which runs in another thread - libuv

For example i have 2 threads. I want to stop server from main thread (Thread 1).
Thread 1: main program
Thread 2: TcpServer
From libuv library:
/*
* This function will stop the event loop by forcing uv_run to end
* as soon as possible, but not sooner than the next loop iteration.
* If this function was called before blocking for i/o, the loop won't
* block for i/o on this iteration.
*/
UV_EXTERN void uv_stop(uv_loop_t*);
That means, if i would call uv_stop(tcp_server_loop) in main thread and the server loop will be blocked because of no events on the tcpserver, then the server will be still in the loop till some event appears. (it probably checks if uv_stop was called before the loop goes to the block mode to wait for new events).

If you run uv_run with UV_RUN_DEFAULT, it will be a blocking call. However, if you use uv_stop then uv_run will immediately return. Remember that the only function in uv that is thread safe is uv_async_send, so if you want to call uv_stop on your TcpServer loop, you will have it to do from within the loop.

Related

Stopping a pthread which is in sleep

I have a thread (This is a Pthread in C implementation) which reads a value from a file every 5 secs. During shutdown, this causes an issue where the shutdown process wants to delete the thread but since it's sleeping, it has to wait for 5 secs for the sleep
to be done and then delete. How can I stop the thread even if it's in sleep as soon as I get the shutdown signal?
I already have a condition variable where the thread sleeps only if the condition is true (i.e - thread is running).
Scenario - As soon as the thread entered sleep, the shutdown signal is received; we have no way to proceed but to wait for the sleep to be completed.
Let's say
if (isThreadRunning == true)
{
sleep(5)
}
As soon as the shutdown signal is received the condition variable is made to be false. But even in this case, there is a chance that the signal might come just after 1st second we need to wait for 4 more seconds
The use of condition variable …
How can I stop the thread even if it's in sleep as soon as I get the shutdown signal?
There are a few ways to handle this.
Does this thread actually need be joined?
If not, simply call exit in the main thread, and this thread will disappear into the void.
The problem with this approach is that there might be some necessary cleanups which this thread must perform.
Instead of calling sleep(5), use pthread_cond_timedwait, with the condition of "thread should continue running".
When the pthread_cond_timedwait returns, check the condition. If true, read the number from the file and go back to pthread_cond_timedwait. If false, return from the thread function.
The main thread should signal the condition and then join the thread.
Note that spurious wakeups are possible, and so you should also check whether 5s have passed since the last time you've read the file.
Instead of sleep(5), use usleep(1000). When usleep returns, first check whether you should keep running, and if so, whether 5s have elapsed since last time your read the file.
This solution is a kind of "busy wait" -- the thread will wake up much more than necessary.
But it's simple and bounds the longest delay on shutdown to 1ms.

Function timeouts in C and thread

Hello everyone i have a question about timeouts in c so i ask you guys.
So i'm making a server application in C that uses POSIX threads to accept multiple simpultenious connections but implementing timeouts was harder than i expected as i read the message (HTTP requests) in parts first the start line than the headers etc, etc, and i initialy used select() to detect if the socket was ready for reading but that way if the client sends the start line only than the server will continue waiting for the headers and body without ever timing out so what i did is i put all the code that reads the message in one function and i wan't to implement a timeout for the entire function, say if the function doesnt return in x seconds than a timeout function is called and the thread is exited...
[Things that i have tried]
putting multiple select calls (one for every socket read) but that ended up in a mess of having to calculate remaining time for each operation.
i didn't actually try to use an alarm signal as i've heard that signals effect the entire process and not a specific thread that would cause one time out to timeout every parallel connection..
thanx in advance.. B)
There is no proper way to terminate a thread function other than letting it finish.
Every attempt to finish a thread from the outside could lead to resource (mostly but not only memory) leaks, state variables in nondeterministic state, and so. Please don't do it. Never. The normal way of terminating a thread function from the outside is to make it listen to some means of inter thread communication (which can be a sync object, a volatile variable or even a message loop), and exit the function core when it is necessary. Normally you would realize it by having a single test in the cycle condition of the thread if it is looping or testing before every long-running operation inside your thread.
Now if you store the timestamp of the function start and test at every cycle condition/long-running test if currenttimestamp > timestamp + timeout, you can exit from inside your thread and voilá; your problem is solved.

Method of checking whether a thread returned or not?

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.

One thread controlling many others

I have an application that waits for clients to connect. Each time a client connects, a new frame gets created (with the new socket file descriptor). I know how many clients will connect, after I reach that number I just run pthread_join in a for loop.
My problem is that I would like the main thread to control all the other threads. My goal is to have each thread send the same message back to the client, at the same time, and only once. There are multiple messages a thread can send.
My current thinking is to define a list of command, as follows:
char *commands[] = {
(char*) "TERMINATE\0",
.... };
And then specify a command number that represents which command to use in that char* array. All threads will do something like
write(sockfd, buffer[commandNumber], length[commandNumber]);
I thought about waiting on a condition variable, but I see two problems:
1) I want to make sure that each thread, although synchronized, execute the command only once.
2) The main thread that initiates the command has to know when all those threads is done executing the command.
Only way I see to execute 2) is to keep track of a counter (with mutexes), and when each thread executes the command, it can increase that counter. I am not sure I will be able to avoid a thread from running the command twice.
What is the best possible way please to coordinate multiple threads to execute a single action at once; and also be able to know when that action has finished executing for every thread please?
You might use a barrier to gate the operation.
Synchronizing the send
The main thread initializes a barrier named "Ready" to N+1. Then it begins accept()ing N client connections, spawning a worker thread for each. The new worker threads immediately wait on barrier "Ready".
After spawning the Nth (and last) worker, the main thread sets the desired command (perhaps using a global commandNumber). Then the main thread waits on barrier "Ready". As soon as all workers and the main thread have arrived (reaching the barrier's limit of N+1), all threads are released, knowing that they are ready to issue their command immediately.
(A common alternate approach is to use a predicate and condition variable rather than a barrier. For example, the main thread might spawn the Nth worker and then cond_broadcast() that it has set a flag ready = 1. This approach is flawed. The main thread cannot know that the Nth worker — or, indeed, any of the workers — are yet waiting on that condition. The barrier solves this problem.)
Indicating completion
Another N+1 barrier, "AllDone", could be used to indicate that the workers are all done. A semaphore initialized to -N and posted by workers would do the same. Having the workers close() their connections and the main thread select()ing or poll()ing connections would convey the same information, too.

What to do when waiting for a event to finish

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.

Resources