I have written a C program that uses two threads for reading and writing. I have declared the variable which are accessed by both the threads as Global. How to avoid the use of global variables in this case.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
You can make structs. I usually to use a struct called
globalArgs
where I put all there global variables.Something like this:
Or, you can pass all values as parameters to functions that needs of.
Please look into following methods of
pthread
library in C for having exclusive access of Shared Global variables in C:Similarly, you can look into Semaphores for synchronizing the use of global variables in C threads.
I think you're asking how to avoid having your threads accessing globals by passing them their work-data during startup.
Please see the last parameter to pthread_create, which allows you to define a user-defined custom pointer that can be anything you want. Use that to pass data (such as a struct address or even by-value so long as the value can fit in the platform's size of a void pointer.
For example, a parent can send a child thread data by doing such:
The child proc would reference this by:
I hope this makes sense, and hope it helps you understand how to pass data to a thread proc, which was what I think your question is.
Do you truly need a shared variable, or do you actually need 2 copies of the same data for each thread? If so, instead of declaring it global, pass it as an argument to the thread at creation.
If it truly needs to be shared, it will need to be protected by a mutex. You can still also do away with the global variable if you bundle the shared variable into a struct along with the mutex and pass it along to the threads as an argument at creation.
There is no need to avoid global variables. Only thing you have to consider is valid data by some lock mechanism.
Putting all global variables in to a struct is for readability and code control when your project grows.
I suggest you to use mutex lock.. Here is an modified sample code.