How to know pthread is stopped? - c

I am new in programming world. I need to move some part of code from kernel space to userland. However, I cannot find the replacement of kthread_should_stop() in pThread. May I know how should I use below code in userland?
while(!kthread_should_stop()){
...
}
Thanks

There is nothing magic about kthread_should_stop(); the kthread_stop() function just sets a boolean variable and wakes up the thread.
Depending on what mechanism you are already using to communicate between threads, you can use a Pthreads condition variable or an eventfd or something like that to implement the stop signal.

Related

Is there any thread safe variable for Pthreads, i need to pass data from one thread to other

Im new to implementation of pthreads
Im using pthreads for two separate actions but in some cases i will have to use data updated from first thread to be used by the other, so just a global variable, with mutex will work or is there any particular variable to be used?
Another thing is that how can i make a pthreads wait until a particular condition is achieved, now i use a "if" condition, but here, thread will be running continuously(Utilizing system recourses) and if condition is satisficed that piece of code works
I was looking for something like an interrupt is it possible?
similarly stopping a pthread, should i use pthreadexit?
Mutex + variable is sufficient. For second part of your question, please read about conditionals and how to use it with pthread (good start point can be https://linux.die.net/man/3/pthread_cond_signal)

Is there a way to immediately block a pthread after creating it?

Basically, I just want to create a pthread for each number of threads available on the machine, without doing any work. I want to somehow block each one at the start and add it to a threadpool so I can pull an available pthread from the pool when I need work to be done.
How do I go about blocking without having a pthread doing any work? I've tried a dummy function but that doesn't seem to work.
Thanks
Just have it start off by waiting on the work queue. This would normally involve pthread_cond_wait or sem_wait or similar depending on what type of synchronization primitives you're using to manage the work queue.

C: How to make threads communicate with each other?

Interesting that this seems to be a basic question, and yet I couldn't find any example of it for the C language (in SO, I found only for Python, C# and C++).
The point is: as a Qt programmer, when I need to make some data to be transmitted between different threads, I start a signal-slot connection between then and use the emit signal mechanism to do the work.
But now I'm working in a C application for Embedded Linux where I need to do a similar work, but I don't have Qt's mechanism available. The question is: how can I make two or more threads communicate with each other in C in a manner similar to that of Qt with signals and slots?
I know that one of the ways to share data is with global variables with changes protected by mutexes. But even then I would probably be unable to do the system in a asynchronous way: I would have to have a loop that would constantly check if the variable has changed or not. But what if I want to execute a specific method of a thread just after another one finished some work (so, in an asynchronous way)? Then it seems such way fails.
Note: although I'm using Embedded Linux and, therefore, mentioning some options that would take POSIX functions and other "Linux-related ways" would be helpful, it would still be better for the community if more time is given to solutions that are not based strictly to one specific platform (if that is possible).
Read a good tutorial on pthreads. You want to know more about condition variables to be used with mutexes.
Condition variables and mutexes should probably be enough for your needs.
You could also use most traditional inter-process communication mechanisms between threads, e.g. a pipe(7) (probably with poll(2)...). So read Advanced Linux Programming and study syscalls(2) and pthreads(7)
Avoid using signal(7)-s between threads and be aware of signal-safety(7). See however signalfd(2), eventfd(2), userfaultfd(2) (you might cleverly handle SIGSEGV with it) and take inspiration from the approach suggested by Calling Qt functions from Unix signal handler.
Observe a running multi-threaded Linux process with strace(1), ltrace(1), gdb(1). You'll understand that several pthreads(7) primitives are using futex(7).
Both GNU glibc and musl-libc are open source and implement the pthreads specification (and Glib, GTK, Qt or POCO are built above them). I invite you to study their source code.
One way is to use message passing between threads via asynchronous queues. This way you can avoid using shared data between threads and only the queues need to be thread-safe.
Asynchronous queues can be implemented using different synchronisation primitives:
Pipes or sockets.
Queues protected with a mutex and a condition variable.
Non-blocking or lock-free queues.
Thread which you want to notify of an event like "data available" can register a callback function which can be trigerred by the notifier thread. You can use a function pointer for this.
Ex: Thread 2 registers a callback function for one or more events. Thread 1 on occurrence of the condition or event calls the registered function.
producer and consumer threads should capture each other's tid. producer on producing can send:
pthread_kill(consumerID, SIGUSR1);
consumer is setup with the signal handler for SIGUSR1, and can retrieve the produced result from the common std::queue saved by pthread_setspecific().
producer and consumer can continue their tasks without being locked by semaphore or cond var/mutex.

Threading problems with GTK

I'm building a fairly simple C application using GTK, but have to perform some blocking IO which will trigger updates to the GUI. In order to do this, I start a new pthread right before gtk_main() as such:
/* global variables */
GMainContext *mainc;
/* local variables */
FILE *fifo;
pthread_t reader;
/* main() */
mainc = g_main_context_default();
pthread_create(&reader, NULL, watch_fifo, argv[argc-1]);
gtk_main();
When the pthread reads some data, it updates the GUI like so:
g_main_context_invoke(mainc, set_icon, param);
Where set_icon is
gboolean set_icon(gpointer data)
{
char *p = (char*)data;
gtk_status_icon_set_from_icon_name(icon, p);
return FALSE;
}
This all works most of the time, but every now and again I get this curious error message:
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
mktrayicon: xcb_io.c:274: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
I thought the whole point of using g_main_context_invoke was to avoid issues with threads? Doing a bit of Googling, I came across gdk_threads_init, gdk_threads_enter and friends, but they all seem to be deprecated? I know the GTK documentation says that all GUI updaes should be performed on the main thread, but this does not combine all that well with blocking IO, and I'd prefer not to have to construct some complex communication mechanism between the threads.
And so, my question is, how should I correctly deal with this?
EDIT: The full code can be seen here
EDIT2: As an update based on #ptomato's answer, I've moved to GThreads and using gdk_threads_add_idle() as seen in this commit, but the problem is still present.
Call XInitThreads(). This should be done before gtk_init, that will stop the messages!
Something like this:
#include <X11/Xlib.h>
...
XInitThreads();
...
gtk_init(&argc, &argv);
I don't remember seeing these messages before GLIB 2.32, when
g_thread_init()/gdk_threads_init() were used.
You might want to check out g_thread_pool_new and g_thread_pool_push.
From thread, use g_main_context_invoke to execute in main loop or
just wrap thread between gdk_threads_enter()/gdk_threads_leave()
I do not use a tray so I can not easily check this. I think you are
correct about gdk_threads_add_idle using locks to protect GTK/GDK API.
There is nothing obvious to me that would cause these messages to
appear. The function description for gtk_status_icon_new_from_icon_name
states that "If the current icon theme is changed, the icon will be
updated appropriately. Which to me, implies your code is not the only
code that will access the X display, which could potentially be the
problem.
There is also some related info regarding XInitThreads() at
What is the downside of XInitThreads()?
Note that while GDK uses locks for the display, GTK/GDK do not ever
call XInitThreads.
On a side note: What's protecting the global variable "onclick", which
is passed to execl after a fork(), The child will not inherit the parent's
memory locks, and GLib mainloop is incompatible with fork().
Maybe you could copy the string to local variable.
I'm not sure if bare pthreads are guaranteed to work with GTK. You should use the GThread wrappers.
I think what the problem may be is that g_main_context_invoke() is adding set_icon() as an idle function. (It seems that that is what goes on behind the scenes, but I'm not sure.) Idle functions added using GLib's API, despite being executed on the main thread, need to hold the GDK lock. If you use the gdk_threads_add_idle() API (which is not deprecated) to invoke set_icon(), then everything should work properly with threading.
(Although this is just a wild guess.)
As a work around, if you just want to avoid blocking the UI while waiting for some IO you could use the asynchronous IO from GIO. That would avoid you having to manage threads yourself.
Edit: Thinking about it you could just mark your file descriptors as non-blocking and add them as a source to the glib main loop and it will poll them for you in the main event loop without having to mess about with threads.
You could avoid using threads by using gio_add_watch() which will invoke your callback function when there is data available on the channel.

pausing main thread execution other than sleep() in C

I need to pause the execution of the main thread with out using sleep statement.
is there any function or status values that shows the alive status of other threads like isalive() in java?
pause() often works well; it suspends execution until a signal is received.
Standard C provides no way to pause the main thread, because standard C has no concept of threads. (That's changing in C201X, but that new version of the standard isn't quite finished, and there are no implementations of it.)
Even sleep() (which is a function, not a language-defined statement) is implementation-specific.
So it's not really possible to answer your question without knowing what environment you're using. Do you have multiple threads? If so, what threading library are you using? Pthreads? Win32 threads?
Why does sleep() not satisfy your requirements? (Probably because it pauses all threads, not just the current one.)
(Hint: Whenever you ask "How do I do X without using Y?", tell us why you can't use Y.)
Consult the documentation for whatever thread library you're using. It should provide a function that does what you need.
A extremely simple approach would be using something as simple as getchar().
Other approach could be waiting for a signal with pthread_cond_wait (or any other similar function in a different threading API).
Other approach could be sitting on a tight loop and using a semaphore (or something simpler like a global variable value) to wait for the other threads to finish.
Anyway, there are several options. You don't say enough about your problem to tell what's your best choice here.
select() is often a good choice.
On Linux, epoll() is often a good alternative to select().
And every program, "threaded" or not, always has "main thread". If you're actually using threads, however, look at pthread_cond_wait().

Resources