pthreads reading and writing to the same variable - c

I know I am supposed to use mutexes but the way I currently use pthreads it would overly complicate the program...
anyway I basically have a variable which I use to denote if a thread is currently performing work or not. in the main thread I run over it in a while loop the check what threads are no longer busy. Now obviously my thread can write to this same variable once it is done.
Is it allowed to read and write from the same variable from 2 different threads, if 1 thread is ONLY reading and 1 thread is ONLY writing. reading of an old version is not of much concern since it will just read the correct once on the next iteration.
so is it safe to do something like that?

In general, NO.
The following article explains why:
http://www.domaigne.com/blog/computing/mutex-and-memory-visibility/
Here is a list of API functions that act as memory barriers:
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11

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)

C difference between main thread and other threads

Is there a difference between the first thread and other threads created during runtime. Because I have a program where to abort longjmp is used and a thread should be able to terminate the program (exit or abort don't work in my case). Could I safely use pthread_kill_other_threads_np and then longjmp?
I'm not sure what platform you're talking about, but pthread_kill_other_threads_np is not a standard function and not a remotely reasonable operation anymore than free_all_malloced_memory would be. Process termination inherently involves the termination of all threads atomically with respect to each other (they don't see each other terminate).
As for longjmp, while there is nothing wrong with longjmp, you cannot use it to jump to a context in a different thread.
It sounds like you have an XY problem here; you've asked about whether you can use (or how to use) particular tools that are not the right tool for whatever it is you want, without actually explaining what your constraints are.

Exclusive access to resource from multiple threads

Is there something equivalent to SIGSTOP and SICONT for threads? Am using pthreads.
Thanks
An edit:
I am implementing a crude form of file access syncronization among threads. So if a file is already opened by a thread, and another thread wants to open it again, I need to halt or pause the second thread at that point of its execution. When the first thread has completed its work it will check what other threads wanted to use a file it released and "wake" them up. The second thread then resumes execution from exactly that point. I use my own book keeping datastructures.
I'm going to tell you how to do things instead of answering the question. (Look up the "X Y problem".)
You are trying to prevent two threads from accessing the same file at the same time. In other words, access is MUTually EXclusive. A "mutex" is designed to do this. In general, it is easier to find help if you search for what you are trying to do (prevent two threads from accessing the same resource simultaneously) rather than searching for how you want to do it (make one thread wait for the other).
Edit: It sounds like you actually want many readers but one writer. This is probably the second most common synchronization problem (after the "producer-consumer" problem). Use a pthread_rwlock: readers call pthread_rdlock and writers call pthread_wrlock.
If you're doing something this sophisticated, you really should start reading the relevant literature. If you think you can do multithreaded programming some serious reading, you are much smarter than me and you don't need my help. I recommend "The Little Book of Semaphores" which is a free download (source). It's not about pthreads, but it's good stuff. The readers-writers problem you are asking about is found under ยง4.2 in the chapter "Classical Synchronization Problems" (heck, this problem is even mentioned in the blurb).
Multithreaded programing is HARD with capital letters and a bold font.
Well, there is pthread_kill.
But you almost certainly do not want to do this. What if the other thread holds (e.g.) a mutex for the heap, and you try to call new while it is stopped?
Since you do not know what the runtime is doing with mutexes, there is no way to avoid this kind of problem in general unless you completely avoid the standard library.
[edit]
Actually, come to think of it, I am not sure what happens if you target a specific thread with SIGSTOP, since that signal usually affects the whole process.
So to update my answer, I do not believe there is any standard mechanism for suspending a thread asynchronously... And for the reason mentioned above, I do not think you want one.
Depending on your application, Pthreads supports what can be considered more refined mechanisms, such as http://www.unix.com/man-page/all/3t/pthread_suspend/ and Mutex mechnisms

Execute 2 different functions concurrently, is pthread my answer?

I have a fixed size array (example: struct bucket[DATASIZE]) where at the very beginning I load information from a file. Since I am concerned about scalability and execution time, no dynamic array was used.
Each time I process half of the array I am free to replace those spots with more data from the file. I don't have a clear idea on how I would do that but I thought about pthreads to start 2 parallel tasks: one would be the actual data processing and the other one would make sure to fill out the array.
However, all the examples that I've seen on pthreads show that they are all working on the same task but concurrently. Is there a way to have them do separate things? Any ideas, thoughts?
You can definitely have threads doing different tasks. The pattern you're after is very common - it's called a Producer-Consumer arrangement.
What you are trying to do seems very similar to standard concurrent program called producer-consumer (look it up, you surely find an example in pthreads). This program has one fixed size buffer which is processed by consumer and filled by producer.
Yes, that's an excellent use for pthreads: it's one of the very things that pthreads was made for.
You might think about fork( )ing twice, once to create the process to do the data manipulation; and then a second fork( ) to create the process that fills in the blanks. Use a mutex to let each process protect the array from the other process and it will work fine.
Why would your array need a mutex? How would you set it up? When would each process need to acquire the mutex and when would it need to release the mutex?
-- pete

How to signal a buffer full state between posix threads

I have two threads, the main thread 'A' is responsible for message handling between a number of processes. When thread A gets a buffer full message, it should inform thread B and pass a pointer to the buffer which thread B will then process.
When thread B has finished it should inform thread A that it has finished.
How do I go about implementing this using posix threads using C on linux. I have looked at conditional variables, is this the way to go? . I'm not experienced in multi threaded programming and would like some advice on the best avenue to take.
Thanks
If you relax the conditions that the buffer must be full before B starts processing it and that the buffer must be empty before A starts filling it again, then this is the classic producer-consumer problem.
If you cannot relax those conditions, then I do not see the benefit of separating the functionality between two threads. Since thread A cannot add to the buffer while thread B is processing, and thread B cannot do any processing while thread A is adding to the buffer, then all the work can be done in a single thread.
Yes, conditional variables and mutexes are two things you have to use when implement your solution.
You can take a look at the section "A few ways to use threads" on explanation how to do it.
How about using a posix semaphore to represent 'number of filled buffers'. The pointers could be passed over a shared ring buffer. Depending on how you want to handle overflows, you may need to protect it with a mutex.

Resources