I have threads in my application that wait on condition variable. When the codition is good thread starts to work and reads some data. My data is global variable. Is it possible pass data on runtime without using global data? I read something about specific data but i don't know if it is useful in this case. Thank you!
Yes, you can pass this to your thread routine: pthread_create(thread, attr, function, *USER_ARG*). Simply create a struct for the data you need for the thread to execute.
Where *USER_ARG* is stored in memory is important, you will often want to use the free store (malloc it) for the argument, otherwise you may corrupt the stack of the thread which called pthread_create.
Related
I want to determine whether certain function in C can be called from multiple threads at the same time, in order to understand if I need to protect it with mutexes. The file where the function is implemented and defined does not have any mutex mechanism, so there is a chance that only one thread ever accesses the function but there is a chance that multiple threads do.
I thought to add a thread local storage variable which I increment upon starting the function and decrement upon exiting the function. If, after decrementing, the value of the variable is greater than 0, then multiple threads access the function.
This is my code:
#include <stdio.h>
static __thread int threadCounter = 0;
void f(void)
{
threadCounter++;
// do something
threadCounter--;
printf("threadCounter: %d\n", threadCounter);
}
a'm wondering if this solution is sufficient to determine whether multiple threads access a function and whether there are better ways to accomplish this.
From the GCC documentation :
"Thread-local storage (TLS) is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread."
Thus, your solution will always indicate that only one thread access your function at the time even if it's not the case. You should use a variable that is shared between thread. But using a volatile one is still not a good solution because if there are multiple thread accessing it at the time, the value might not be the good one.
In conclusion, I think the better way of doing this would be to setup a mutex and using the pthread_mutex_trylock function to detect if there are multiple threads trying to call your function.
A thread local variable is by definition only visible for the current thread, your solution won't work. But your approach is good. Instead of using a thread local variable you should use a variable protected by a mutex.
This test either is using a local variable, or it isn't thread-safe in itself. In either case, it won't be useful as proof. If you want to use a counter, you have to protect it with something like a mutex or critical section. There's pretty much no way around this.
But there's a another way to do this better though, giving you exact information of who called the function, while at the same time not having to modify the actual function. You can create a "mock" function:
#define f() ( print(__func__), f() )
This prints the name of the thread callback function, then calls the actual function f(). This works because the pre-processor token f() is evaluated before any function call.
I wrote the function as a custom one print, since you'll still have the problem with multiple thread trying to access stdout at once if you use printf etc. So the custom print function must contain the means of thread-safety.
I met some confusions when writing a C program.
My scenario has 2 thread but they run serial, so at one time there's single thread. I want to save a parameter in my first thread and I want to get it in my second thread. (pthread here)
So is there anyway to realize this? Public static parameter will be recycled when the thread ends because it belongs to the current thread. I want to save a value or pointer in current process instead of thread so that I can attach it in my next thread...
Is there any possible way to realize this?
Thanks so much!
Threads share the memory. Use a variable (either global, local to the creating thread, or at the heap) and pass a pointer to both threads that points to that very variable.
I need to know how a thread can send its ID to another thread before it goes to wait state. I thought to pass a variable with its ID but I don't know how to do it.
If it's only one thread and its parent, you could use a global variable, as they are shared between all threads. Make it volatile in case you expect concurrent access.
EDIT: I'm not sure if you're using POSIX threads on Linux but you probably have a way to pass a pointer (e.g. to a struct) when creating the thread. It could contain a variable to store its ID or a pointer to a function to call on the parent thread. I know you can do it with Windows threads.
You can create a pointer in the thread which is pointing to the function in the parent (by reference). By the time it goes to wait state then it can just use that pointer to trigger something to its parent.
Threads share memory, so you can allocate a global variable and let the child write on it.
Than for the synchronization (aka inform the parent that a value has been written) you have many choices: you can use a semaphore, can send a signal from the thread back to its parent, use a synchronization variable like explained here.
Is it possible for two threads to use a single function "ThreadProc" as its thread procedure when CreateThread() is used?
HANDLE thread1= CreateThread( NULL, //Choose default security
0, //Default stack size
(LPTHREAD_START_ROUTINE)&ThreadProc,
//Routine to execute. I want this routine to be different each time as I want each thread to perform a different functionality.
(LPVOID) &i, //Thread parameter
0, //Immediately run the thread
&dwThreadId //Thread Id
)
HANDLE thread2= CreateThread( NULL, //Choose default security
0, //Default stack size
(LPTHREAD_START_ROUTINE)&ThreadProc,
//Routine to execute. I want this routine to be different each time as I want each thread to perform a different functionality.
(LPVOID) &i, //Thread parameter
0, //Immediately run the thread
&dwThreadId //Thread Id
)
Would the above code create two threads each with same functionality(since thread procedure for both of the threads is same.) Am I doing it correctly?
If it is possible then would there be any synchronization issues since both threads are using same Thread Procedure.
Please help me with this. I am really confused and could not find anything over the internet.
It is fine to use the same function as a thread entry point for multiple threads.
However, from the posted code the address of i is being passed to both threads. If either thread modifies this memory and the other reads then there is a race condition on i. Without seeing the declaration of i it is probably a local variable. This is dangerous as the threads require that i exist for their lifetime. If i does not the threads will have a dangling pointer. It is common practice to dynamically allocate thread arguments and have each thread free its arguments.
Yes, it is very well possible to have multiple (concurrent) threads that start with the same entry point.
Apart from the fact that the OS/threading library specifies the signature and calls it, there is nothing special about a thread entry point function. It can be used to start off multiple threads with the same caveats as for calling any other function from multiple threads: you need synchronization to access non-atomic shared variables.
Each thread uses its own stack area, but that gets allocated by the OS before the Thread Procedure get invoked, so by the time the Thread Procedure gets called all the special actions that are needed to create and start a new thread have already taken place.
Whether the threads are using the same code or not is irrelevant. It has no effect whatsoever on synchronization. It behaves precisely the same as if they were different functions. The issues with potential races is the same.
You probably don't want to pass both threads the same pointers. That will likely lead to data races. (Though we'd have to see the code to know for sure.)
Your code is right. There is NOT any synchronization issues between both threads. If they need synchronization, it maybe because they are change the same global variable, not because they use the same thread Procedure.
How does one modify a threads data from outside a thread?
If a thread is running a function that loops for the runtime of the application, how can its data be set, changed?
How does one call functions which modify a specific threads functions?
Where do these functions belong?
The advantage and disadvantage of threads is that they share the memory space with every other thread in the process. You can use any form of data transfer you would use in single threaded applications to pass data betweens segments of you application. However, in a multi-threaded application you must use some type of synchronization to assure data integrity and prevent deadlocks.
If the "thread's data" you want to modify from outside is in the form of local variables in a function running in the thread, or thread-specific data created with the __thread extension, then the only way you can modify them from outside (modulo code with UB that's technically just trashing memory) is by having the thread take the addresses of its variables and store that somewhere where other threads can see it (either in a global variable, or at a location passed in via the thread start function's void * argument.
Also note that, as rerun pointed out, you have to use some method of synchronization if multiple threads are accessing the same data. The only standard/portable synchronization methods are the pthread ones: pthread_mutex_lock etc., but you can also use assembly or compiler intrinsics (like __sync_* in gcc).